11

I would like to execute code that is specific to remote PSSessions. That is, the code doesn't apply locally, but applies to all remote sessions.

Is there any environment variable, function or cmdlet that would effectively return true if I'm in an active PSSession and false if I'm running locally?

Kris Harper
  • 5,672
  • 8
  • 51
  • 96

2 Answers2

14

Check if the $PSSenderInfo variable exists. 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.

Community
  • 1
  • 1
Shay Levy
  • 121,444
  • 32
  • 184
  • 206
0

You could also test using this:

If ( (Test-Path variable:PSSenderInfo)
        -and ($Null -ne $PSSenderInfo)
        -and ($PSSenderInfo.GetType().Name -eq 'PSSenderInfo') ) {
    Write-Host -Object "This script cannot be run within an active PSSession"
    Exit
}

This was not my initial finding, but it helped with "variable PSSenderInfo not set" issue, if it doesn't exist.

Robbie P
  • 335
  • 3
  • 10
  • No need for all this tests. This command line is sufficient: `if($PSSenderInfo){'I am in a remote session'}` – Luke Jun 20 '23 at 07:37