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.

  • have you configured winrm?
    – tony roth
    Apr 5 '13 at 16:52
  • @tony - yes i have
    – rakesh
    Apr 5 '13 at 20:43
  • 2
    In what way is it failing? Error message please.
    – Straff
    Apr 13 '15 at 7:49

Executing a Remote Command

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.

Starting a Remote Session

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>

Source: http://www.howtogeek.com/117192/how-to-run-powershell-commands-on-remote-computers/


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:

  1. Start a PowerShell session
  2. Run the command specified in the $EXE variable
  3. Wait for it to finish
  4. Terminate the session

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
$EXE='"<path to exe>"'
$Arguments=@(<array of arguments>)
$ScriptString="Start-Process -FilePath $EXE -ArgumentList @('$(Arguments -join "','")') -WindowStyle Hidden -Verb RunAs -Wait"
$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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.