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 PowerShell Scripting
Related Q&A from Don Jones
If you don't need a GUI display, PowerShell can be hosted in several hosting applications so you can use cmdlets instead of a graphical input prompt.continue reading
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
Each PowerShell version has different features made useful by add-ins and snap-ins, so admins have to pay attention to what features work where.continue reading
Have a question for an expert?
Please add a title for your question
Get answers from a TechTarget expert on whatever's puzzling you.