Why does the `using` scope work locally with Start-Job, but not Invoke-Command?

This is true when using “using” because the definition of using states,

Beginning in PowerShell 3.0, you can use the Using scope modifier to identify a local variable in a remote command

Anytime you use the $using, you have to provide -ComputerName or -Session arguments whether the target server is localhost or remote.

Ex.

$myServerName="www.google.com"
Invoke-Command { ping $using:myServerName }
### BIG ERROR.

$myServerName="www.google.com"
Invoke-Command { ping $using:myServerName } -computername $env:COMPUTERNAME
### Ping response.

$myServerName="www.google.com"
Invoke-Command { ping $myServerName }
### Ping Reponse.

$using: is only supported in a few, specific contexts, which have one thing in common: code that is being run outside the current runspace – all other contexts neither require nor support it. (@mklement0)

[Invoke-Command, Start-Job, and InlineScript are known contexts which support the use of $using: to pass variables in current local session.]

Documentation on where you can use $using

Leave a Comment