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:
- Hostname: server1
- Fully Qualified Domain Name: server1.example.com
- IP Address: 192.168.10.50
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.
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:
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.