How do I run commands on a remote machine with admin privilege (example: running as Run as Administrator) using PowerShell.
So far I have tried
start-process powershell.exe -verb runas -argumentlists ".\test.ps1"
This is failing.
Server Fault is a question and answer site for system and network administrators. It only takes a minute to sign up.Sign up to join this community
Use the Invoke-Command cmdlet to run a command on a remote machine. The syntax is as follows:
Invoke-Command -ScriptBlock <COMMAND> -ComputerName <COMPUTER> -credential <USERNAME>
COMMAND is the command you want to run, COMPUTER is the remote machine’s hostname, and USERNAME is the username of the account under which you want to run the command. You will be prompted for the password.
Use the Enter-PSSession cmdlet to start a remote PowerShell session in which you can run multiple commands using the Session parameter of Invoke-Command:
Enter-PSSession -ComputerName <COMPUTER> -Credential <USERNAME>
Invoke-Command cannot be used in instances where elevation is required. Additionally, I found the accepted answer to be a bit incomplete. In my case, however, I wanted to run an
.exe file instead of a script, but I believe my solution can be adapted to handle scripts as well.
The script below will:
Don't terminate the session before the job is complete or you will kill the process you started. To run this in parallel, remove the
-Wait argument from
Start-Process and watch the jobs before terminating the sessions.
# Enter or already have some administrative-level credentials here $Cred=Get-Credential $EXE='"<path to exe>"' $Arguments=@(<array of arguments>) $ScriptString="Start-Process -FilePath $EXE -ArgumentList @('$(Arguments -join "','")') -WindowStyle Hidden -Verb RunAs -Wait" $ScriptBlock=[System.Management.Automation.ScriptBlock]::Create($ScriptString) $Session=New-PSSession -ComputerName <target computer> -EnableNetworkAccess -Name <name of session> -Credential $Cred $Job=Invoke-Command -Session $Session -ScriptBlock $ScriptBlock -AsJob Wait-Job -Job $Job > $null Remove-PSSession -Session $Session