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 }
Mark is an Independent Microsoft Teams Consultant with over 15 years experience in Microsoft Technology. Mark is the founder of Commsverse, a dedicated Microsoft Teams conference and former MVP. You can follow him on twitter @UnifiedVale