We also have a ScriptBlock parameter where we’ll encapsulate the commands we intend to run on the remote computer. You can see below how this works in action. I’m running the hostname command locally on my computer and then running it remotely with I nvoke-Command. PS C:\> Invoke-Command -ComputerName SRV1 -ScriptBlock $scriptblock PS C:\> Invoke-Command -ComputerName SRV1 -ScriptBlock You can see that it returns different results. You may not have noticed but the Invoke-Command command created a lightweight session in the background to run that command and when the command was complete it tore it down. This is more obvious when you choose to run commands interactively using the Enter-PSSession command. The Enter-PSSession command allows you to log into a remote session, run commands, get output and work just as if you were typing commands into the local console. To do this though, first, you need to establish a session. One way to do that is to use the ComputerName parameter. Notice below that I’ve entered a remote session and have a new PowerShell prompt that’s prepended by the computer name the session is running in. PS C:\> Enter-PSSession -ComputerName SRV1Īt this point, I can run any commands I’d like, and they will be executed on the remote computer. We don’t need to use Invoke-Command to do this. When we’re done, we have to close the session.
Related: Installing Chocolatey Packages Remotely With PowerShell To do that, we use the exit keyword which disconnects us from the session and closes it. You can see below once we type exit and hit Enter, we’re immediately brought back to our local console. PowerShell Remoting is a convenient way to execute commands on remote computers.