Getting Local Variables into Remote Sessions

There are at least three ways to get your local variables into your remote sessions. I’ve written these in preferential order beginning with the best option. Don’t forget to read about_Remote_Variables (Get-Help -Name about_Remote_Variables) to learn more, and see more examples.

$Word1 = 'PowerShell'
$Word2 = 'on'
$Computer = 'Server1'

# Using Scope Modifier
# (1st Option -- works in PowerShell 3.0 and up)
Invoke-Command -ComputerName $Computer -ScriptBlock {
    Write-Verbose -Message "$Using:Word1 $Using:Word2 $env:COMPUTERNAME (Using Scope Modifer)" -Verbose
}
VERBOSE: PowerShell on Server1 (Using Scope Modifier)


# Param
# (2nd Option -- works in PowerShell 2.0 and up)
Invoke-Command -ComputerName $Computer -ScriptBlock {
    Param($Word1InParam,$Word2InParam)
    Write-Verbose -Message "$Word1InParam $Word2InParam $env:COMPUTERNAME (Param)" -Verbose
} -ArgumentList $Word1, $Word2
VERBOSE: PowerShell on Server1 (Param)


# Args
# (3rd Option -- works in PowerShell 2.0 and up)
Invoke-Command -ComputerName $Computer -ScriptBlock {
    Write-Verbose -Message "$($args[0]) $($args[1]) $env:COMPUTERNAME (Args)" -Verbose
} -ArgumentList $Word1, $Word2
VERBOSE: PowerShell on Server1 (Args)

2 thoughts on “Getting Local Variables into Remote Sessions

    1. tommymaynard Post author

      It should, if you’re using Invoke-Command. It’s that command that allows you to run other commands as though you’re at/on the remote computer. It’s that command that would require you to send in local variables if there’s information/things on the local computer that you need to get to/want on the remote computer. Without an example, I’m not 100% you’re setting things up correctly…

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *