Windows – force user logoff script for Windows 7

user-accountswindows 7

Is there any way to force another user to logoff via command line in Windows 7 Home Premium?

My work VPN policy requires that there be only 1 user logged in, to log the other users off I have to run the command prompt as administrator, run the task manager and then right click and log them off. This is a little annoying. Ideally, I'd like an executable or batch script to run that did it all in one quick step. I've ran across a couple threads talking about logging users off after a set timeout, and that might work ok too (assuming there are any that work…my findings are that there aren't) – but I'd still like to know how to do it in one step if possible.

Is there any way to do what I am asking?

I'm not opposed to writing a .net app if I have to as well.

Best Answer

You could automate the logoff command, using something like this batch file (adapted from here):

@echo off
query session > c:\temp\session.txt
for /f "skip=2 tokens=2,3,4" %%i in (c:\temp\session.txt) DO if not "%%i"=="Geoff" logoff %%j
del c:\temp\session.txt
pause

This uses the query session command to get a list of sessions, then the for command to parse the output, and finally the logoff command to log off other users. You'll want to run the query session command to check the output on your machine.

On my machine, I get:

C:\Users\Geoff\Desktop>query session
 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
 services                                    0  Disc
>console           Geoff                     1  Active

the first two lines are garbage, so the skip 2 part ignores those. The username, ID and State get put into the i, j, and k variables respectively. You'll want to test it, and if it won't run as a non-administrator user then you can either right-click the file on your desktop and 'Run as Administrator', or you can create a shortcut to the batch file, then select Properties | Shortcut | Advanced | Run as Administrator. Either way you'll get a UAC prompt. Finally, if you want to run the batch file without the UAC prompt, you can go the more obscure task scheduler route: see this post.