I'm trying to use the following code from th question "PowerShell: Running a command as Administrator" to not only self elevate my script to run automatically in an Administrator-level PowerShell, but also for the Administrator-level PowerShell session to be run with an ExecutionPolicy level of RemoteSigned. I'm assuming that I need to use something like -ExecutionPolicy RemoteSigned in $newProcess.Arguments but am completely lost as to if this is the case, and if it is then what the syntax do I use to create the the multiple arguments?
# Get the ID and security principal of the current user account
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);
# Get the security principal for the administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;
# Check to see if we are currently running as an administrator
if ($myWindowsPrincipal.IsInRole($adminRole)) {
# We are running as an administrator, so change the title and background colour to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)";
$Host.UI.RawUI.BackgroundColor = "DarkBlue";
Clear-Host;
} else {
# We are not running as an administrator, so relaunch as administrator
# Create a new process object that starts PowerShell
$newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter with added scope and support for scripts with spaces in it's path
$newProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Start the new process
[System.Diagnostics.Process]::Start($newProcess);
# Exit from the current, unelevated, process
Exit;
}
# Run your code that needs to be elevated here...
Write-Host -NoNewLine "Press any key to continue...";
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown");
$newProcess.Arguments is indeed where you add the relevant parameters. However, you may want to run the script via the parameter -File instead of using the call operator (&) in an implicit -Command parameter.
$newProcess = New-Object Diagnostics.ProcessStartInfo 'powershell.exe'
$newProcess.Arguments = '-ExecutionPolicy RemoteSigned -File "' +
$script:MyInvocation.MyCommand.Path + '"'
$newProcess.Verb = 'runas'
[Diagnostics.Process]::Start($newProcess)
Related
I wrote some code on my Windows 7 administration machine, where it just worked fine. Now I want to run it from a console - commandline with administration access from a client machine on Windows 10.
The script throws the error when it tries to Register the task through the COM-Object of the Task-Scheduler:
Value does not fall within the expected range:
# Aufruf in der command line mit
# powershell.exe -file C:\Workspace\controlling-macros\TaskCreator.ps1
$path = "C:\Workspace\controlling-macros\FullWorkbookPathsMR.csv"
$csv = Import-CSV -Path $path -Delimiter ";" | % {
# The name of the scheduled task
[string]$TaskName = "$($_.reportsource) - $($_.reportname) - $($_.reportid)"
# The description of the task
[string]$TaskDescr = "Hello, it's you again! I am $($_.reportname) and I will get started, when Report ID $($_.reportid) is fired. Have a nice day!"
# The Task Action command
$TaskCommand0 = "cmd"
$TaskCommand1 = "`"C:\Program Files (x86)\Microsoft Office\Office14\EXCEL.EXE`""
# The Task Action command argument
$TaskArg = "/c C:\Windows\System32\taskkill.exe /F /IM EXCEL.EXE"
$TaskArg1 = "$($_.fullpath)"
# attach the Task Scheduler com object
$service = new-object -ComObject("Schedule.Service")
# connect to the local machine.
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa381833(v=vs.85).aspx
$service.Connect()
$rootFolder = $service.GetFolder("\")
$TaskDefinition = $service.NewTask(0)
$TaskDefinition.RegistrationInfo.Description = "$TaskDescr"
$TaskDefinition.Settings.Enabled = $true
$TaskDefinition.Settings.AllowDemandStart = $true
$triggers = $TaskDefinition.Triggers
#http://msdn.microsoft.com/en-us/library/windows/desktop/aa383915(v=vs.85).aspx
$trigger = $triggers.Create(0) # Creates an "On an event" trigger
$trigger.Subscription = "<QueryList><Query Id='0'><Select Path='Application'>*[System[Provider[#Name='$($_.reportsource)'] and EventID='$($_.reportid)']]</Select></Query></QueryList>"
# "*[System[Provider[#Name='$reporttype'] and EventID=$reportid]]"
# http://msdn.microsoft.com/en-us/library/windows/desktop/aa381841(v=vs.85).aspx
$Action = $TaskDefinition.Actions.Create(0)
$action.Path = "$TaskCommand0"
$action.Arguments = "$TaskArg"
$Action = $TaskDefinition.Actions.Create(0)
$action.Path = "$TaskCommand1"
$action.Arguments = "$TaskArg1"
#http://msdn.microsoft.com/en-us/library/windows/desktop/aa381365(v=vs.85).aspx
$rootFolder.RegisterTaskDefinition("$TaskName", $TaskDefinition, 6, "System", $null, 5) # <<--- here the error occurs
Write-Host $($_.sequence) $($_.reportsource) $($_.reportname) $($_.reportid) $($_.fullpath) "task created successfully."
}
why no data is piped to the variables?
I know this seems basic but I would start by matching Powershell versions first as different versions of Powershell do compile some code differently as well as some cmdlets just do not work in older versions.
In new-scheduledtasksettingsset there is a compatibility switch (v1, vista, win7, win8).
Edit5: Adam's code works unless there are spaces in the path. That solution is at Powershell Opening File Path with Spaces
Edit4: Simplified further with a test for the path. Same Error.
If ($args[0] -eq "admin")
{
$TheScriptPath = "C:\Users\root\Desktop\script.ps1"
Test-Path ($TheScriptPath)
Start-Process "powershell -noexit" $TheScriptPath
}
Else { Write-Host "OK" }
Output when I call "powershell .\script.ps1 admin" is:
True
Start-Process : This command cannot be run due to the error: The system cannot find the file specified.
At C:\Users\root\Desktop\script.ps1:11 char:2
Edit3: Nevermind. Previous solution stopped working. Script is:
if ($args[0] -eq "admin)
{
$TheScriptPath = $myInvocation.MyCommand.Definition
Start-Process powershell -Verb runAs -Workingdirectory $PSScriptroot $TheScriptPath
exit
}
Write-Host "Ok"
Error when I call "powershell .\script.ps1 admin" is:
Start-Process : This command cannot be run due to the error: The system cannot find the file specified.
At C:\Users\root\Desktop\script.ps1:11 char:2
It's not even working when I hard-code the script path now, even with "-Verb runAs" removed.
Edit2: This is solved, I just can't accept my own answer for two days. Hopefully I remember to do that in case someone else comes along with this question.
Edit1: My script now reads:
If ($args[0] -eq "go")
{
$ThePath = $myInvocation.MyCommand.Definition
Start-Process powershell -Verb runAs $ThePath
Exit
}
Write-Host "OK"
It fails with the error below. However, if I hard-code the script path and write the script as:
If ($args[0] -eq "go")
{
Start-Process powershell -Verb runAs C:\Users\root\Desktop\script.ps1
Exit
}
Write-Host "OK"
It succeeds. I've also tried ""$myInvocation.MyCommand.Definition"" to no avail.
Original:
I have a powershell script that, at least in Windows 7, elevated the user and then ran the rest of the script. In Windows 10, however, it's giving me:
Exception calling "start" with "1" argument(s): "The system cannot find hte file specified"
At C:\Users\root\desktop\script.ps1:15 char:2
If ($True)
{
# We are not running "as Administrator" - so relaunch as administrator
# Create a new process object that starts PowerShell
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Start the new process
[System.Diagnostics.Process]::Start($newProcess);
# Exit from the current, unelevated, process
exit
}
Write-Host "Ok"
The script exists at this path, as it actually attempting to invoke itself. I'm at a loss here.
I'm running Powershell v5.1.15063.1155 on Windows 10 (v10.0.15063 Build 15063). If I run the following:
$context = [Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()
if (-not $context.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Start-Process powershell -Verb runAs -ArgumentList $myInvocation.MyCommand.Definition
exit
}
Get-Date
Sleep -Seconds 4
You can try this as a workaround as it works for me.
To your question, I'd think something is wrong with the the ProcessStartInfo object you created ($newProcess). I've seen that error when the executable name supplied as a parameter can't be found. For example, if I run the following:
$newProcess = new-object System.Diagnostics.ProcessStartInfo "cocain";
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
$newProcess.Verb = "runas";
[System.Diagnostics.Process]::Start($newProcess);
I get the error you described:
You're sure Powershell is in your path (where.exe powershell)? I know its a reach.
I have a requirement to run a script with admin rights by users. So I created 2 scripts where a user runs the first script which will call the second script with start-process with admin credentials. I am passing currently logged in user ID and user profile from first script to second script as arguments to make use of them in the second script. However everything is fine but getting error when accessing user's documents folder in the second script using a variable to the path.
First script as below.
$currentusername = $env:USERNAME
$currentuserprofile = $env:USERPROFILE
$adminusername = "domain\admin"
$adminPassword = 'pwd' | ConvertTo-SecureString -Force -AsPlainText
$credential = New-Object
System.Management.Automation.PsCredential($adminusername, $adminPassword)
$scriptpath = "path to second script.ps1"
Start-Process -filepath PowerShell.exe -Credential $credential -argumentlist "-noexit", "-executionpolicy bypass","-file $scriptpath",$currentusername,$currentuserprofile
Second Script.ps1
param (
#$currentusername = $args[3],
$currentuserprofile = $args[5]
)
$UserDir = "$currentuserprofile\Documents\"
Test-Path $UserDir
this test-path $UserDir is giving false.
Can anyone have had this issue or help me on to overcome this?
When you pass in argument to powershell.exe along with -file only the arguments AFTER the file path are passed onto the script. Reference
So technically, in your 2nd script, you only have the following arguments:
$args[0] # $currentusername
$args[1] # $currentuserprofile
That being said, generally you don't use $args and param together. It's one or the other.
you can either do this:
$currentusername = $args[0]
$currentuserprofile = $args[1]
$UserDir = "$currentuserprofile\Documents\"
Test-Path $UserDir
OR
param (
$currentusername,
$currentuserprofile
)
$UserDir = "$currentuserprofile\Documents\"
Test-Path $UserDir
Even though you're passing admin user credentials, by default, the process is not started with elevated permissions, add -verb RunAs to the start-process to achieve that.
I want to call a "PS App Deployment Toolkit"-package (Link) from a PowerShell-Script with arguments.
The mentioned "PS App Deployment Toolkit"-package is a powershell-script, which I want to call with parameters. (Call a .ps1 from a .ps1)
I want to use splatting for the parameters.
I want to wait for the script to end.
I want to get the exit-code from the script.
Here is my code, which is not working:
$PSADToolKitInstallWrapper = "C:\Temp\MyPackage\PS-AppDeploy.ps1"
$PSADToolKitParameters = #{
"DeploymentType" = "Uninstall";
"DeployMode" = "Interactive";
"AllowRebootPassThru" = $True;
"TerminalServerMode" = $False;
"DisableLogging" = $False;
}
$InstallStatus = Start-Process -FilePath "PowerShell.exe" -ArgumentList $PSADToolKitInstallWrapper #PSADToolKitParameters -Wait -PassThru
Write-Host "Exit-Code: $( $InstallStatus.ExitCode )"
This Line would work fine, but I want to set the Parameters like in the example above:
$InstallStatus = Start-Process -FilePath "PowerShell.exe" -ArgumentList "$PSADToolKitInstallWrapper","-DeploymentType Install -DeployMode Silent -AllowRebootPassThru -TerminalServerMode" -Wait -PassThru
Could you please assist me to get this working?
Thank you!
I don't think you need to try so hard. Why run powershell.exe from inside a PowerShell script? You're already running PowerShell. Just run the command line you want:
$PSADToolKitParameters = #{
"DeploymentType" = "Uninstall"
"DeployMode" = "Interactive"
"AllowRebootPassThru" = $True
"TerminalServerMode" = $False
"DisableLogging" = $False
}
C:\Temp\MyPackage\PS-AppDeploy.ps1 #PSADToolKitParameters
If the path and/or filename to the script you want to run contains spaces, then call it with the invocation operator (&) and quote the filename; example:
& "C:\Temp\My Package\PS-AppDeploy.ps1" #PSADToolKitParameters
Checking the results of the script depends on what the script returns. If it returns an output object, then you can simply assign it:
$output = C:\Temp\MyPackage\PS-AppDeploy.ps1 ...
If the script runs an executable that sets an exit code, you check the value of the $LASTEXITCODE variable (this is analogous to the %ERRORLEVEL% dynamic variable in cmd.exe).
I am very new to powershell and I'm not sure what I did wrong. It is running fine on my Windows 8 PC but when I send it to someone else (he has Windows 7; created this for him), he gets a not allowed to run scripts error.
Tried with -ExecutionPolicy RemoteSigned but still no luck.
##################
<# CONFIG START #>
##################
#replace the path with your steam path. For example: C:\Program Files (x86)\Steam\Steam.exe
$steam_path = "C:\Program Files (x86)\Steam\steam.exe"
#You can change it to Ethernet 1 or Ethernet 2 or Ethernet 3 etc depending on which adapter you want to disable.
#If you have custom name for them (you can rename them from control panel), have to use that name.
$adapter_name = "Ethernet 1"
<#
What program to run.
1: Steam Dota 2
2: Steam CS
3: Steam CSS
4: Steam CSGO
5: Custom Program 1
6: Custom Program 2
7: Custom Program 3
#>
$game_id = "5"
<# Custom Program path and arguments#>
$cp1_path = "C:\Program Files (x86)\counter-strike source\css.exe"
$cp1_arg = " "
$cp2_path = ""
$cp2_arg = " "
$cp3_path = ""
$cp2_arg = " "
$delay = 20
################
<# CONFIG END #>
################
"Checking admin permissions..."
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
"Administrator permissions required."
$arguments = '-ExecutionPolicy RemoteSigned -file "' + $myinvocation.mycommand.definition + '"'
# $arguments
Start-Process powershell -Verb runAs -ArgumentList $arguments
Break
}
"Exiting Steam..."
Start-Process -FilePath $steam_path -ArgumentList "-shutdown" -Wait:$true
Start-Sleep -s 2
"Disabling Network Adapter..."
Disable-NetAdapter -Name $adapter_name -Confirm:$false
Start-Sleep -s 5
"Starting Game..."
Switch($game_id)
{
1
{
Start-Process -filepath "steam://rungameid/570"
}
2
{
Start-Process -filepath "steam://rungameid/10"
}
3
{
Start-Process -filepath "steam://rungameid/240"
}
4
{
Start-Process -filepath "steam://rungameid/730"
}
5
{
Start-Process $cp1_path -ArgumentList $cp1_arg
}
6
{
Start-Process $cp2_path -ArgumentList $cp2_arg
}
7
{
Start-Process $cp3_path -ArgumentList $cp3_arg
}
}
Start-Sleep -s $delay
"Enabling Network Adapter..."
Enable-NetAdapter $adapter_name -Confirm:$false
exit
If you sent him the script, then RemoteSigned is doing it's job just fine. He got the script remotely (from you) and it is not signed, so it won't be executed.
Tell your friend to navigate to the ps1 script in Windows Explorer and right click, then choose "Unblock." He will then need to restart the PowerShell instance if it has failed to run the script already since this kind of information is cached by Windows.
The error indicates you didn't correctly set the execution policy. Firstly, you have run Powershell as an administrator. To do this, right click on the Powershell icon in the start menu and click on "Run as Administrator". Next you have to run the following command in Powershell:
Set-ExecutionPolicy RemoteSigned
You will be prompted to allow the change. Type "Y" and press return.
Finally, try running your script.