Derrick Moeller
Derrick Moeller

Reputation: 4970

Filtering line from text file in a batch file

I have been tasked with creating a logon script that will logoff a users abandoned sessions. I have found this from Microsoft which looked like a promising start.

I have modified Microsoft's script and currently have this.

query session %username% >session.txt
for /f "skip=1 tokens=3," %%i in (session.txt) DO logoff %%i
del session.txt

This generates a session.txt like the following.

 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE 
 rdp-tcp#66        someuser                  3  Active                      
>rdp-tcp#67        someuser                 12  Active                      

My script currently skips the first line, parses the two remaining lines and logs off the sessions by ID. I would like to change this behavior such that I only logoff the abandoned session(3) and not my current session(12). Can I identify and filter the line containing >?

Upvotes: 1

Views: 381

Answers (1)

npocmaka
npocmaka

Reputation: 57332

you don't need a log file . this will just slow down your script:

for /f "skip=1 tokens=3 eol=>" %%a in ('query session %username%') do set "sessionToKill=%%a"
echo %sessionToKill%

eol=> will skip every line starting with > . You can put the logoff logic directly in the for loop instead of the set.

Upvotes: 3

Related Questions