Wednesday 4 July 2012

DOS: Disconnect from ALL Citrix sessions with one batch file

I am pretty happy with myself for coming up with this.  It did take awhile, but it's working.

First let me start off by saying that we are concerned with the security aspect with keeping information safe but we need to also provide a suitable workflow to help facilitate others with ease of use and help broaden the functionality of the tools they already use.

Here is the Batch file contents.
@echo off
SETLOCAL ENABLEDELAYEDEXPANSION
for /f %%A in ('QFARM ^| find "*"') DO (
        SET curSERVER=%%A
        SET curSERVER=!curSERVER:~0,-1!)
for /f %%A in ('QFARM ^| find "CITRIX"') DO (
        SET SERVER=%%A
        SET lastCHAR=!SERVER:~-1!
        IF NOT !lastCHAR! == * for /f "skip=1 tokens=2" %%B in ('QUSER %USERNAME% /SERVER:!SERVER!') DO (
        tsdiscon %%B /SERVER:!SERVER!
         )
)
for /f "skip=1 tokens=2" %%A in ('QUSER %USERNAME%') do (
        tsdiscon %%A /SERVER:%curSERVER%)
An important note:  This is run from within Citrix... I found that when using the QUERY command locally you don't have access to the QFARM command, but in a Citrix context you do.  We also needed to run this within Citrix because we have generic logins in some locations that act as thin clients, so the %USERNAME% variable would not be effective in this case.

tsdiscon is a great tool that was overlooked initially.

Firstly we wanted to find out what the current server we are on is.  This was necessary because if you end up disconnecting from the server you are running this from, it stops.

Secondly... we loop through the output of the QFARM command finding "CITRIX"... if you have different naming conventions, you just have to massage that a little and it's good to go.

QFARM by itself spit output with the citrix servers and one of the servers has an asterisk at the end... this is one that we want to skip over until the end...  its the %curSERVER% variable.

From there on you can see... we loop through the servers finding the ica-tcp#... sessions and use that to disconnect from each of the servers.

I hope this is informative and helps you out!