PowerShell Remoting Data
Remote data is values you send into a remote command and values it sends back. Data travels with the command, and results travel back with the answer.
Send one value into the block
ArgumentList carries the value. Param gives it a name inside the block.
Invoke-Command -ScriptBlock { param($n) "Hello $n" } -ArgumentList "Ana"Send two values and get a value back
List two values in ArgumentList. The block adds them and sends the sum back.
$sum = Invoke-Command -ScriptBlock { param($a, $b) $a + $b } -ArgumentList 3, 4
$sumThe using shortcut fails without a remote computer
The using shortcut only works when the block runs on a remote computer. A local run fails with a real message.
$name = "Ana"
try {
Invoke-Command -ScriptBlock { "Hello $using:name" } -ErrorAction Stop
} catch {
"Caught: " + $_.Exception.Message
}Example
$name = "Ana"
$age = 31
$result = Invoke-Command -ScriptBlock { param($n, $a) "$n is $a years old" } -ArgumentList $name, $age
$resultKey points
- ArgumentList: the values you send into a remote block.
- Param: the names inside the block that receive those values.
- Order matters: values arrive in the same order you listed them.
- Return values: the block sends its result back to you.
- Using scope: a shortcut that pulls a local variable into a remote block.
In this example, two local values are sent into the block with ArgumentList. Param names them inside the block. The block builds one sentence and sends it back.
Note
The using shortcut only works on a real remote computer. On this machine it fails, so this lesson sends values with ArgumentList instead.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How do you send a value into an Invoke-Command block on this machine?