How do I run commands on a remote machine with admin privilege using powershell

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
$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