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:
Invoke-Command –ScriptBlock (param($c) Add-Computer –Credential $c }
-ComputerName 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:
Invoke-Command –FilePath 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.
Dig Deeper on Windows administration tools
Related Q&A from Don Jones
With some simple configuration, admins can run a PowerShell script each time a computer starts with the help of the Task Scheduler GUI and cmdlets. Continue Reading
Wondering how to get PowerShell to read XML files? Our expert explains a few methods you could use. Continue Reading
One of the most common PowerShell questions is how to format the output so it's more presentable. Our expert offers some insight. Continue Reading