How to Pass variables from local PS Session to Remote PS Session

When writing scripts for admin tasks I wanted to explore the idea of running scripts locally on a management workstation rather than RDP to each server and run a command. The Invoke-Command can achieve this nicely. However, what if I wanted to pass a declared variable from my management workstation to the remote PS Session?

e.g. $Ping = “www.google.co.uk”

This is set on my management workstation Powershell session. But I want to test I can ping this from another server or web address. In order to do this we need to declare the variable $Ping in our Invoke-Command -Scriptblock  and -ArgumentList parameters.

Invoke-Command -Session $PSSessionName -ArgumentList -Scriptblock {
Param(
$Ping
)
Test-Connection -Computername $Ping
}

This will output

Source        Destination     IPV4Address      IPV6Address                              Bytes    Time(ms)  PSComputerName
——        ———–     ———–      ———–                              —–    ——–  ————–
WIN-83AIC7… http://www.google.c… 74.125.230.87                                             32       38        WIN-83AIC7KIGI1.test.domain
WIN-83AIC7… http://www.google.c… 74.125.230.87                                             32       42        WIN-83AIC7KIGI1.test.domain
WIN-83AIC7… http://www.google.c… 74.125.230.87                                             32       36        WIN-83AIC7KIGI1.test.domain
WIN-83AIC7… http://www.google.c… 74.125.230.87                                             32       36        WIN-83AIC7KIGI1.test.domain

If you are using Powershell 3.0 you can use the $using scope modifier instead of declaring Parameters or Argumentlists like so

Invoke-Command -Session $PSSessionName -Scriptblock {
Test-Connection -Computername $using:Path
}

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s