#PSTip How do I determine if my script is running in a RDP session?

If you list the Environment drive, you’ll find a variable called SESSIONNAMESESSIONNAME is defined only if the Terminal Services system component is installed.

PS> Get-ChildItem env:\s*
Name                           Value
----                           -----
SystemDrive                    C:
SystemRoot                     C:\Windows
SESSIONNAME                    Console

The value of the variable is set to ‘Console’ which means that you’re currently running directly on the local machine. However, when you initiate a remote desktop session to another machine, the value of the variable will be different, such as: ‘RDP-Tcp#0’.

Based on that, we can determine if our code is running inside a remote desktop session.

if($env:SESSIONNAME -eq 'Console')
    Write-Host "You are running on the local machine."
    Write-Host "You are in a Remote desktop session ('$env:SESSIONNAME')."
Share on:
comments powered by Disqus