12

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?

2 Answers 2

15

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.

Sign up to request clarification or add additional context in comments.

1 Comment

depending on your use case you may also want to check $PSSenderInfo.ConnectionString -ne 'http://localhost' because Start-Job {$null -ne $PSSenderinfo} | receive-job -wait -AutoRemoveJob is $true
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.

1 Comment

No need for all this tests. This command line is sufficient: if($PSSenderInfo){'I am in a remote session'}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.