1

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:

  1. 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.
  2. If zero active users:
    • Logoff any actual users (not system processes) that are in a disconnected state
    • Delete C:\MyFolder\*
  3. 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.

  • I would consider looking at my answer [here](http://stackoverflow.com/a/29130697/3829407) which converts qwinsta output into a PowerShell object. Makes it easier to query the data. – Matt May 07 '15 at 01:54

1 Answers1

0

Windows Server 2012 R2 + Powershell 4.0 = No more text parsing!

Have a look here Url: https://technet.microsoft.com/en-us/library/jj215451(v=wps.630).aspx

and use the following commands to query

  1. Query the users: Get-RDUserSession
  2. Log off the user ID which is disconnect with Invoke-RDUserLogoff

Regards, Glenn

Glenn G
  • 146
  • 3