Why doesn't PowerShell allow the use of the using
scope when using Invoke-Command
locally? According to the documentation, the using
modifier can only be used on remote commands. To quote:
Beginning in PowerShell 3.0, you can use the Using scope modifier to identify a local variable in a remote command.
This behavior can be demonstrated when running Invoke-Command
locally:
$myServerName = 'www.google.com'
Invoke-Command { ping $using:myServerName }
Which throws the following error:
A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer.
The error indicates that the remote use of the using
modifier is only valid remotely, with Invoke-Command
. So, if we try running the same thing using Start-Job
, what happens?
$myServerName = 'www.google.com'
$j = Start-Job { ping $using:myServerName }
while( $j.State -eq 'Running' ){ Start-Sleep -s 1 }
Receive-Job $j
Which doesn't throw an error, and I get the output I expect:
Pinging www.google.com [172.217.6.132] with 32 bytes of data:
Reply from 172.217.6.132: bytes=32 time=20ms TTL=56
Reply from 172.217.6.132: bytes=32 time=19ms TTL=56
Reply from 172.217.6.132: bytes=32 time=19ms TTL=56
Reply from 172.217.6.132: bytes=32 time=19ms TTL=56
Why does the documentation state that the using
scope modifier only works remotely when it can be clearly used in local contexts as well? And similarly, if it works in the context of a local Start-Job
, what stops it from working with a local Invoke-Command
?