Home > Mobile >  script to find and kill windows RDS session using powershell
script to find and kill windows RDS session using powershell

Time:06-02

I am working on an automation to create users for temporary session and delete them along with their home directory after a specific duration.

User creation and deletion is handled using Ansible ansible.windows.win_user module. User's home folder deletion is handled using ansible.windows.win_file module. The ansible is run from my linux server.

They are all working fine. But the home folder deletion is not working always, it fails to delete the home folder when the user is not logged out.

So, I want to forcefully kill the user session before running the delete home folder command.

I can do the function manually in powershell by getting the session ID using the following command

qwinsta | Select-String -Pattern <username>

I get the following output.

<username> 4 Disc

here 4 is the session id, and then I can kill the session id using the following command

rwinsta /server:servername 4

Now, I need a programmatic way to only get the session id to kill the user session. I can do the same in linux using awk command eg: qwinsta | Select-String -Pattern | awk ('print $2') but I am not sure about similar command on windows.

To wrap up, I know the windows username and I need to forcefully log him out.

CodePudding user response:

Split it on whitespace and pick the 2nd array element:

(-split '                   <username>           4  Disc')[1]

4

Various ways to parse qwinsta or quser: Easier way to parse 'query user' in PowerShell (or quser)

CodePudding user response:

why can't use logoff ? To log off a user from a session by using the name of the session and server, for example session TERM04 on Server1, type:

logoff TERM04 /server:Server1

check this out https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/logoff And also work using username with rwinsta also

rwinsta {<sessionname> | <sessionID>} [/server:<servername>] [/v]
rwinsta TERM04 /server:Server1

As an addon , it is better delete profile registries if you want completely delete a user profile. Else may cause temporary profile problem when the same user try login back.

  • Related