PowerShell Remoting

By: Cam Wohlfeil
Published: 2018-02-06 0000 EST
Category: Programming
Tags: powershell

When it comes to remoting in PowerShell, there's two main options: Invoke-Command (good) and Enter-PSSession (bad, but necessary sometimes). The difference is that Invoke-Command will do as the name says, invoke the command for you and return the output. Enter-PSSession will change the context of your PowerShell to that of the specified computer until the session is exited. Now you may be asking why I say one is good and the other bad. The reason for this is that in a modern IT environment you should never be doing things on an individual server, you should be using a DevOps configuration model that makes this unnecessary. Invoke-Command however can be convenient when used with foreach to quickly get information or make a change on many machines for testing and emergency fixes.

Invoke-Command -ComputerName <ComputerName> {<command>}

Enter-PSSession -ComputerName <ComputerName>
Exit-PSSession

Note: Invoke-Command can be passed multiple comma separated hostnames (or piped a PowerShell object), and even a script by using -FilePath.

Bonus: You can run certain commands remotely without even opening a session, like Restart-Computer, which can just be passed a multiple comma separated hostnames (or piped a PowerShell object) via -ComputerName.

More Info: