#PSTip How can I tell if I’m in a remote PowerShell session?

Note: This tip requires PowerShell 3.0 or above.

There are times where you’ll want to determine if the session your code is running in is a remoting session. For a quick test you can check the value of $Host.Name. If it’s ServerRemoteHost, you are in a remote session (works in v2.0). For a more robust solution you can use the existence of the $PSSenderInfo variable (exist in v2.0). From about_Automatic_Variables:

$PSSenderInfo
   Contains information about the user who started the PSSession,
   including  the user identity and the time zone of the originating
   computer. This variable is available only in PSSessions.

   The $PSSenderInfo variable includes a user-configurable property,
   ApplicationArguments, which, by default, contains only the
   $PSVersionTable from the originating session. To add data to the
   ApplicationArguments property, use the ApplicationArguments parameter
   of the New-PSSessionOption cmdlet.

Here we connect to a remote server and we’re also adding out our own custom value to the $PSSenderInfo variable.

We’re using the new inline syntax, available in PowerShell 3.0, to create a new session object, which is passing a new value (in the form of a hash table) that will be stored in the $PSSenderInfo variable. Once we connect to the remote computer, we can check its value. In addition to the default content of $PSSenderInfo, we can also find our custom value:

PS> Enter-PSSession Thor -SessionOption @{ApplicationArguments=@{MyKey="MyValue"}}
[Thor]: PS C:\Users\psmag> $PSSenderInfo.ApplicationArguments

Name                           Value
----                           -----
PSVersionTable                 {CLRVersion, WSManStackVersion, PSVersion, BuildVersion...}
MyKey                          MyValue

[Thor]: PS C:\Users\psmag> $PSSenderInfo.ApplicationArguments.MyKey
MyValue
Share on: