Search code examples
powershellclient-serverinvoke-command

Run .ps1 on remote machine


I need to execute powershell script on remote computer with admin privilegies. I have 2 scripts: client and server. When i start client.ps1 i invoke command on server machine but get access error. I get no error if I use simple code in server.ps1 like write-host "hello".

server.ps1:

 Get-service -ComputerName 'client'

client.ps1:

$ScriptBlockContent = { 
        d:\server.ps1
        }
$remote=New-PSSession -ComputerName 'server'
Invoke-Command $remote -ScriptBlock $ScriptBlockContent

Solution

  • Your problem is authentication. You have to enable the server to use your credentials for that. You can do this by using CredSSP.

    1. Enable this on your client:

      Enable-WSManCredSSP -Role Client -DelegateComputer ServerNameHere

    2. Enable it on your server:

      Enable-WSManCredSSP -Role Server

    3. Now add this to your Invoke-Command:

    -Credential Domain\YourUsername -Authentication CredSSP

    A remark on that: With CredSSP, its easy to steal your credentials, if you connect to a compromised system (same as RDP). Be sure that you do this on secure computers only.