1

#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')."
}
Filed in: Columns, Tips and Tricks Tags: ,

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

  1. PetSerAl says:

    Environment variables can be stale since they do not change on reconnect. A way to check if session is active local session or not:
    [System.Diagnostics.Process]::GetCurrentProcess().SessionId-eq(Get-ItemProperty HKLM:System\CurrentControlSet\Control\Terminal` Server GlassSessionId).GlassSessionId

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: