Using $using in PowerShell for local variables in remote sessions

When running scripts that connect to remote systems using Invoke-Command, you can use your local variables in the remote session which makes things a lot easier. In this blog post, I will show you how 🙂

What are remote variables?

“You can use variables in commands that you run on remote computers. Assign a value to the variable and then use the variable in place of the value.

By default, the variables in remote commands are assumed to be defined in the session that runs the command. Variables that are defined in a local session, must be identified as local variables in the command.”

Source: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_remote_variables?view=powershell-7.4#long-description

How does this work?

If you have a script or function that has parameters, for example, and you want to use those in a remote system using Invoke-Command, then you can use the $using:variable to pass those during execution.

In the example below, I use a simple function to connect to a system to start a Windows Service and set the Startup Type to Automatic. (And yes, you can do this using Get-Service and Set-Service with the -ComputerName parameter… But this is just an example 🙂 )

param (
    [Parameter(Mandatory = $true)][String[]]$ComputerName = $env:COMPUTERNAME,
    [parameter(Mandatory = $true)][ValidateSet("Automatic", "Boot", "Disabled", "Manual", "System")][string]$StartupType,
    [Parameter(Mandatory = $true)][String]$ServiceName

)

#Connect to remote system, start the service and configure the service(s) Startup Type
Invoke-Command -ComputerName $ComputerName -ScriptBlock {
    Start-Service -Name $using:ServiceName
    Set-Service -Name $using:ServiceName -StartupType $using:StartupType
    Get-Service -Name $using:ServiceName
}

Running this above against two machines (One Windows 11 client and one Windows Server 2022 in my lab in this case) will use the $ServiceName and $StartupType variables you specify as parameters for the script in the ScriptBlock. (This makes running scripts more flexible than using variables in the script itself.)

Wrapping up

By using the $using remote variable, you can take any local variable into a remote session. You can read more about using it in different scenarios here.

Leave a Reply

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