Intro:
First off, I am very new to scripting in general so the logic behind how I think this should be solved may likely be flawed. I am working with Windows Server 2012 R2 so I figure that PowerShell might be the best approach for this.
What I am trying to do:
Set a scheduled task to run once an evening and call a script that does the following:
- Check to make sure there are zero active users logged in to the local server that is executing the script
- Users in a disconnected state would NOT count as logged in.
- If zero active users:
- Logoff any actual users (not system processes) that are in a disconnected state
- Delete C:\MyFolder\*
- Else, do nothing
The idea is that I don't want to delete C:\MyFolder, but I want to delete the contents within it. I might not be able to delete the contents within C:\MyFolder if a user that is in a disconnected state is the one who owns the contents so to get around that, I log them off (they shouldn't be leaving disconnected sessions anyways).
Logic:
After doing some reading around, I found that qwinsta /server:localhost
seems to query the localhost for users and provide this type of output:
PS C:\Users\EF112131> qwinsta /server:localhost
SESSIONNAME USERNAME ID STATE TYPE DEVICE
services 0 Disc
console 1 Conn
AB123456 2 Disc
rdp-tcp#0 cd789101 3 Active
rdp-tcp#1 EF112131 4 Active
rdp-tcp 65536 Listen
That gives me the logged on users that I care about (AB123456
, cd789101
, and EF112131
) and it checks the respective state of their sessions (Disc
, Active
). My thought is that from here I can pull in the USERNAME
and STATE
into some sort of check. If the check returns any STATE
set to Active
, the script will do nothing and end. If there are no Active
states, the script will disconnect any USERNAME
that is in a Disc
state and then clear the contents of C:\MyFolder by doing something like del /S C:\MyFolder\*
The issue I am having here is that I have no idea how to pull those values from the above output? I would imagine it is something similar to how awk
is in Linux land but I still haven't figured it out.