Invoke-Command Remote Variables PowerShell

Invoke-Command Remote Variables PowerShell

Hello,

Invoke-Command is great to use one of the “fan out” parallel execution possibilities with PowerShell. Indeed, by default it can execute the same command on 32 servers, simultaneously, without knowing anything about threads or runspaces.

Invoke-Command Remote Variables PowerShell

One drawback of this great cmdlet is when you need to use a variable inside the script block that you want to execute remotely. If you don’t pass it as an argument, it will be empty and you can have a non expected behavior on the remote system.

Invoke-Command Remote Variables PowerShell - Not Working
Invoke-Command Remote Variables PowerShell – Not Working

ArgumentList

One of the solution is to pass the variable that you need on the remote system as an argument in Invoke-Command, and then use them as $args in the script block.

Invoke-Command Remote Variables PowerShell - Working
Invoke-Command Remote Variables PowerShell – Working

$Using

Another one is to use the $using scope in the script block:

$MyRemoteVariable = "Am I empty?"
Invoke-Command -ComputerName DC2-Core -ScriptBlock {$using:MyRemoteVariable}
Invoke-Command Remote Variables PowerShell - Using
Invoke-Command Remote Variables PowerShell – Using

And now you can use your local variables on a remote system.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.