I am trying to build a function that will log off any non-administrator user when the function is called. I’m hoping to find a way to whitelist those users so they won’t get logged off, no matter what their idle time or session state is. But any other users with any amount of idle time need to be logged off.
(Long story but suffice it to say that Server Manager in Server 2012 R2 has been acting up on us and is no longer logging people off after x hours of inactivity, and it isn’t accurately reporting idle time… Which is why I’m trying to find a solution with PowerShell in the meantime.)
So, the code below is something I’ve been trying to work on. It doesn’t seem to whitelist as I had expected it to based on the Where-Object -NotMatch part, so I am wondering if I’m missing something or whitelisting isn’t doable by username at all.
Function Logoff-TSUser() { [CmdletBinding()] Param ( [Switch]$ViewOnly ) Begin { Import-Module RemoteDesktop $Collections = (Get-RDSessionCollection).CollectionName Write-Output "Searching for user sessions to end. . ." } Process { ForEach ($Collection in $Collections) { $Sessions = Get-RDUserSession -CollectionName $Collection | Where-Object UserName -NotMatch "Administrator","Admin1","Admin2" ForEach ($Session in $Sessions) { If (($Session).IdleTime -gt 0) { [String]$UserName = $Session.Username [String]$CollectionName = $Session.CollectionName [String]$HostServer = $Session.HostServer Write-Output "Logging off $UserName from $HostServer." If ($ViewOnly -eq $True) {Write-Output "View Only Mode. No logoffs will occur."} Else {Invoke-RDUserLogoff -Force -HostServer ($Session).HostServer.ToString() -UnifiedSessionID ($Session).UnifiedSessionID.ToString()} } $Sessions = $null } } } }
What could I be doing better to get it to work as intended (and is it even possible to get it to work as intended)?
This isn’t a super important or urgent thing; just a workaround until we hear back on our ticket with Microsoft or until the bug with Server Manager is fixed.
Thanks in advance!