PowerShell Using Variables
The $using: scope modifier lets a script block read a variable from outside the block. It is the form used when the block runs on another computer.
A local $using: read fails without a remote computer
There is no remote computer here, so the read fails and the catch prints the real reason.
$name = "Ana"
try {
Invoke-Command -ScriptBlock { "Hello, $using:name" } -ErrorAction Stop
} catch {
"Caught: " + $_.Exception.Message
}Try each loop value in turn
The loop tries one item at a time, and the results are collected in loop order.
$items = @("red", "blue", "green")
$results = foreach ($item in $items) {
try {
Invoke-Command -ScriptBlock { "got: $using:item" } -ErrorAction Stop
} catch {
"Caught for " + $item + ": " + $_.Exception.Message
}
}
$resultsA $using: variable cannot be assigned to
The assignment form is rejected before it can run, so the catch prints the real message.
$name = "Ana"
try {
Invoke-Command -ScriptBlock '$using:name = "Ben"' -ErrorAction Stop
} catch {
"Caught: " + $_.Exception.Message
}Example
$greeting = "Hello"
$names = @("Ana", "Ben")
$results = foreach ($n in $names) {
try {
Invoke-Command -ScriptBlock { "$using:greeting, $using:n" } -ErrorAction Stop
} catch {
"Caught for " + $n + ": " + $_.Exception.Message
}
}
$resultsKey points
- $using: scope modifier: a prefix that makes an outside variable visible inside a script block.
- Use $using: inside an Invoke-Command script block that runs on a remote computer.
- A loop variable can be named with $using: too, so each pass of the loop sends its own value on a remote run.
- Single-machine limit: without a remote computer, the block cannot retrieve a $using: variable, and the error says so.
- A $using: variable is read-only inside the block, so the block cannot change the outside variable.
In this example, a greeting and a list of names are defined first. A loop then tries Invoke-Command once per name, with a $using: read inside each block. Each attempt fails on this machine, so the catch builds one message per name, and the collected messages print in loop order.
Note
locally, a plain variable already works inside Invoke-Command, because the block runs in your own session, so $using: is only needed for remote runs.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Inside an Invoke-Command script block, how do you read the outside variable $name?