ToastIT
February 28, 2020

It's Likely We're Living in a PSSession

Posted on February 28, 2020  •  2 minutes  • 353 words

A question came up on the PowerShell Microsoft Tech Community a couple of days ago that got me thinking.

How can we tell if our PowerShell code is running in a PSSession, and what info can we find about the connection itself.

The question itself was based around the fact that the remote sessions had access to a hash table with settings relevant to specific servers and this had to be queried by name.

The initial attempt involved to using $env:COMPUTERNAME, but there’s a very real possibility that that won’t match what was specified in the hash table and by extension the name used for the remote connection itself.

For example consider three different options you could use to identify a given server:

So… what can we do?

The Magic of Automatic Variables

It turns out that there is an automatic variable that only exists when you’re inside a PSSession: $PSSenderInfo

It contains a lot of information about the originator of the remote connection, including of all things the time zone of the source computer.

Example output from my lab

Example output from my lab

So in order to answer my first question, if the $PSSenderInfo variable exists you can be sure that you’re in a PSSession.

As for the answer to the Tech Community question, the ConnectionString is my go to property. The connection string’s host component mirrors the computer name specified when creating the PSSession.

It would be possible to do some string manipulation to isolate just the host from the entire string… but that is a lot of work.

Instead we’ll turn it into a System.Uri object and make the system do the work for us:

([Uri] $PSSenderInfo.ConnectionString).Host
zannah

Now we know how the remote computer was identified on the originating computer, meaning you can create remote sessions in bulk and take programmatic actions based on this info.

I’m interested in knowing what other uses people may find for the info found inside this automatic variable, let me know in the comments or over on Twitter .

Credit

Hero image by Giu Vicente on Unsplash

comments powered by Disqus
Follow me