Executing Code Remotely

by Dec 3, 2013

In a domain environment, PowerShell remoting is working almost out of the box. All you might have to do is enable Remoting on target machines (beginning with Server 2012, PowerShell remoting is enabled by default for Administrators).

In PowerShell 3.0, to enable remoting manually, that's all (Administrator privileges required):

You do not need to configure anything on the client side (the machine that is going to send commands).

Next, any Administrator can send PowerShell code to the enabled machine and have it execute. This example would list all the PowerShell-related processes from the target machine:

$code = 
      Get-Process -Name powershell*, wsmprovhost -ErrorAction SilentlyContinue

$list = 'server1', 'w2k12-niki', 'pc11box'
Invoke-Command -ScriptBlock $code #-ComputerName $list

When you run the code as-is, Invoke-Command runs the script block stored in $code on your own machine.

It reports all running instances of the PowerShell console, the ISE PowerShell editor, and any hidden PowerShell remoting sessions initiated from someone else on your machine.

Once you uncomment the -ComputerName parameter, the code will run on all of the machines listed in $list variable. Make sure they exist and have remoting enabled. When you receive data from remote computers, PowerShell automatically adds a "PSComputerName" property with the name of the computer that sent back the information.

Twitter This Tip! ReTweet this Tip!