Reference local variables in a remote PowerShell session the easy way

Reference local variables in a remote PowerShell session the easy way

Q. How can I easily reference local variables in a remote PowerShell execution?

A. PowerShell v3 and above makes this very easy. Prior to version 3 to use variables in a remote PowerShell session you needed to pass the variables as arguments for example:

$Name = "John"
Invoke-Command -ComputerName savxvinode1 -ScriptBlock {Write-Output "Hello $args"} -ArgumentList $Name

In PowerShell v3 you can leverage $using: to access local variables, for example:

$Name = "John"
Invoke-Command -ComputerName savxvinode1 -ScriptBlock {Write-Output "Hello $using:name"}

Each week, John Savill answers all of your toughest tech questions about the worlds of Windows Server, Azure, and beyond. Read his past IT advice here, and email your questions to [email protected].

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish