Running remote commands from one Windows machine on another

Sometimes in the process of developing PowerShell automation, it is useful to test the commands and scripts by simply remoting from one host to another.

First add the remote host (the server in our case has an IP of 172.31.39.27) as a trusted host on the client machine

Set-Item wsman:localhost\client\trustedhosts -value 172.31.39.27 

Then create the session. Notice the single quotes aroudn the password. Double quotes don’t seem to play well with the $ in the password.

$s = New-PSSession -ComputerName 172.31.39.27 -Credential (New-Object System.Management.Automation.PSCredential("pliant",(ConvertTo-SecureString 'pa$$w0rd2019' -AsPlainText -Force)))

Finally you can run the commands

Invoke-Command -Session $s -ScriptBlock {echo "Hello World!"}