#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."
}
else
{
    Write-Host "You are in a Remote desktop session ('$env:SESSIONNAME')."
}

About the author: Shay Levy

Shay Levy is a Co-founder and editor of the PowerShell Magazine. He is a multiple-year recipient of the Microsoft MVP award, and a Microsoft Certified Trainer (MCT). Shay often covers PowerShell related topics on his blog and you can also follow him on Twitter at @ShayLevy

Related Posts

%d bloggers like this: