Access Local Variables in a Remote Session with PowerShell

Occasionally I’ll come across a system with PowerShell version 2.0 on it that I need to run a remote command against which needs access to local variables. I can never remember how to accomplish that task so I thought I would write a blog about it as a reminder for myself and others who may find themselves in the same scenario.

I’ll demonstrate each of the available options and whether or not they work on PowerShell version 5.1

$PSVersionTable

var-remote1a.jpg

And PowerShell version 2.0

$PSVersionTable

var-remote2a.jpg

First, I’ll store the name of a process in a variable locally in both the PowerShell 5.1 and 2.0 console sessions I have open:

$ProcessName = 'svchost'

var-remote3a.jpg

Trying to use the local variable in a remote session for either version generates an error message because the variable doesn’t exist in the session on the remote computer:

Invoke-Command -ComputerName dc01 {
Get-Process -Name $ProcessName
}

var-remote4a.jpg

The Using variable scope modifier which was introduced in PowerShell version 3.0 allows the local variable to be successfully used in a remote session on PowerShell 5.1:

Invoke-Command -ComputerName dc01 {
Get-Process -Name $Using:ProcessName
}

var-remote5a.jpg

It generates an error when used with PowerShell 2.0 since that particular feature didn’t exist until PowerShell version 3.0:

Invoke-Command -ComputerName dc01 {
Get-Process -Name $Using:ProcessName
}

var-remote6a.jpg

The ArgumentList parameter can be used with either PowerShell 2.0 or 5.1 to use a local variable in a remote session. If you’re running a version that supports it, I recommend the Using scope modifier instead.

Invoke-Command -ComputerName dc01 -ArgumentList $ProcessName {
Get-Process -Name $args[0]
}

var-remote7a.jpg

PowerShell version 2.0 is deprecated, but that doesn’t mean you won’t have to occasionally deal with a system still running it. Even if the system can be updated, you can’t just take production down in the middle of the day to update the version of PowerShell it’s running.


Related Blog Articles

ยต