Michael Harvey
Michael Harvey

Reputation: 148

Detect if Remote Desktop is active with batch

So, I've been scouring the internet trying to find a way to detect if remote desktop is running. I really never found what I was looking for, so I set out to do it myself. I found that when I query user I get the following result:

 USERNAME          SESSIONNAME        ID  STATE   IDLE TIME  LOGON TIME
>michaelh          rdp-tcp#0           1  Active      none   9/29/2014 11:14 AM

So I used a for loop to find and break apart the line I needed. Here's what I came up with:

@ECHO off

setlocal EnableDelayedExpansion

for /f "tokens=2,4" %%a in ('QUERY USER ^| FINDSTR ">"') DO (

    set "consoleTemp=%%a"
    set "connectionState=%%b"
    set "consoleType=!consoleTemp:~0,7!"

)

SET consoleTypeCorrect=
IF "!consoleType!"=="rdp-tcp" SET consoleTypeCorrect=1

SET connectionStateCorrect=
IF "connectionState"=="Active" SET connectionStateCorrect=1

set TRUE=
set TRUE=%connectionStateCorrect%%consoleTypeCorrect%

IF "%TRUE%"=="11" (
    echo You are connected via !consoleType!
) else (
    ECHO Sorry, the console type is !consoleType!
)

endlocal
PAUSE

This works perfectly, but my question for you guys would be is there's a better way of doing this? If you're looking at this and don't understand how it works, then pm/email me and I'll explain it.

Upvotes: 2

Views: 3188

Answers (1)

Michael Harvey
Michael Harvey

Reputation: 148

Thanks @David Ruhmann for your input! I'll post this as my answer if there isn't a better way to detect if RDP is connected.

@ECHO off

setlocal EnableDelayedExpansion

for /f "tokens=2,4" %%a in ('QUERY USER ^| FINDSTR ">"') DO (

    set "consoleTemp=%%a"
    set "connectionState=%%b"
    set "consoleType=!consoleTemp:~0,7!"

)

SET consoleTypeCorrect=
IF "!consoleType!"=="rdp-tcp" SET consoleTypeCorrect=1

SET connectionStateCorrect=
IF "connectionState"=="Active" SET connectionStateCorrect=1

set TRUE=
set TRUE=%connectionStateCorrect%%consoleTypeCorrect%

IF "%TRUE%"=="11" (
    echo You are connected via !consoleType!
) else (
    ECHO Sorry, the console type is !consoleType!
)

endlocal
PAUSE

Upvotes: 1

Related Questions