When using PowerShell remoting, it's important to differentiate between locally executed code and remotely executed code. If you need to execute something locally and then pass that along to one or more remote computers, there's a specific way to do so -- and it isn't always obvious.
For example, suppose you've created a credential object and want to pass that along to the remote computer to use in a command:
$cred = Get-Credential
You would do this by creating a parameter block in the remote command script block. Then, specify the data to be passed in the –ArgumentList parameter:
(param($c) Add-Computer –Credential $c }
SERVER2 –ArgumentList $cred
The items given to –ArgumentList, which should be in a comma-separated list, are substituted by position into the Param() block. The first –ArgumentList item goes to the first Param() variable, the second goes to the second, and so on. The Param() variables can then be used inside the script block, just like any other variable.
This technique is shown in the built-in help for Invoke-Command. Here's another technique:
MyScript.ps1 –ComputerName SERVER2,SERVER2
The assumption here is that MyScript.ps1 internally defines a Param() block with two parameters -- $this will be sent to the first parameter, and $that will be sent to the second. It's basically the same technique as using a –ScriptBlock, but everything is defined in the script file instead.
About the author
Don Jones is a well-known and respected PowerShell expert and educator. He's co-author of three books on PowerShell (see PowerShellBooks.com for a list). You can find his content online, including his PowerShell Q&A forums, by visiting DonJones.com.
This was first published in February 2013