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.