Quick Learn – PSMonday #13: Monday, July 25, 2016

Topic: PowerShell Remoting Continued II

Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.

We’re not done yet; there’s more to discuss about PowerShell Remoting and specifically the Invoke-Command cmdlet. Again, this is the cmdlet that allows us to run a command, or a series of commands, against a remote computer, or group of remote computers. It does all this without the need for us to interactively type commands on the remote computer(s).

One of the things you may eventually need to accomplish is to get a local variable from your local computer, into a PS Remoting session. Let’s start by creating a local variable. In the below example, we create and assign $LocalVariable and echo its value.

PS > $LocalVariable = $env:COMPUTERNAME
PS > $LocalVariable

TOMMYSPC

We’re going to utilize the Using scope modifier to get this variable to the remote computer. The Using scope modifier was introduced in PowerShell 3.0, and it is the preferred and easiest way to accomplish this task. That version of PowerShell shipped inbox with Windows 8 and Server 2012; however, it could be installed on some down-level versions of Windows (2008 R2 and Windows 7).

Now that we have our local variable set, let’s take it to our remote computer. We reference the local variable in the PS Remoting session, by inserting “Using:” in-between the dollar sign and the variable name.

PS > Invoke-Command -ComputerName MEMSRV01 -ScriptBlock {
    "The local computer is $Using:LocalVariable."
    "The remote computer is $env:COMPUTERNAME."
}

The local computer is TOMMYSPC.
The remote computer is MEMSRV01.

That’s it for now. We’ll continue with this topic next week where we’ll discuss how this was completed prior to PowerShell 3.0, and the Using scope modifier.

Leave a Reply

Your email address will not be published.