How to write a Batch Script that kills terminal sessions? [closed]

I have the following scenario. We have our ERP Programm running on our dedicated windows terminal server, and if all the licenses get full i free them up by manually going onto the terminal server and typing the following commands in my cmd

This command gets as a list of all sessions with an session id

qwinsta /server:localhost

Output looks something like this:

 SESSIONNAME       USERNAME                  ID  STATUS 
 services                                    0  Getr.
 console           Administrator             7  Aktiv
 rdp-tcp#107       administrator             8  Aktiv
                   user1                    14  Getr.
                   user217                  12  Getr.
                   user 456                 23  Getr.


And with this command and the session id from above i kill the session.

rwinsta /server:localhost 14

Now since it's a tideous process i thought: Hey lets write a script and add it to Scheduler to kill all sessions everyday at midnight and since it's a dedicated server we can really kill all sessions.

I know exactly what i want to implement but can't quite figure it out technically.

I started with a rough template: (I know i doesn't make sense yet).
Explanation: Query all Sessions, Short log info about that, from all sessions get the session id and loop over the rwinsta command. When all sessions are killed short log info again.

all_sessions=qwinsta /server:localhost
echo "These are all Sessions ${all_sessions}"
get_session_id=all_sessions
kill_command=rwinsta /server:localhost[ID]
echo "All Sessions Killed"
pause

Solution 1:

The usual way to split the lines into tokes doesn't work here, because the count of tokens isn't constant. So you need a different way to get the numbers (get the last-but-one token):

@echo off
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('quinsta /server:localhost ^|findstr /e "Getr." ^| findstr /v "services console"') do (
  for %%b in (%%a) do (
    if not "%%b" == "Getr." set "sID=%%b"
  )
  ECHO rwinsta /server:localhost !sID!
)

You may need to adapt the strings in findstr /v to your needs.