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?
Check PowerShell Remoting is enabledWhen you run the Test-WSMan command on a local computer then you can see if PowerShell Remoting is enabled or not. Of course, you can run the command for another computer by using the -ComputerName parameter.
Using the WS-Management protocol, Windows PowerShell remoting lets you run any Windows PowerShell command on one or more remote computers. You can establish persistent connections, start interactive sessions, and run scripts on remote computers.
Just run Enter-PSSession -ComputerName localhost. If it enters the remote session, PS remoting is enabled.
PowerShell remoting is enabled by default on Windows Server platforms. You can use Enable-PSRemoting to enable PowerShell remoting on other supported versions of Windows and to re-enable remoting if it becomes disabled. You have to run this command only one time on each computer that will receive commands.
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 theApplicationArguments
property, use theApplicationArguments
parameter of theNew-PSSessionOption
cmdlet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With