Last active
September 13, 2016 15:26
-
-
Save markwragg/001536672bc225346cad83cab642d4f7 to your computer and use it in GitHub Desktop.
A slightly dirty Powershell module which includes a function for converting the results of the command-line Query User in to a Powershell object and a function for logging off disconnected users (with -whatif and -confirm).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example usage: | |
# Get-RDPUser | Disconnect-RDPUser -WhatIf | |
Function Get-RDPUser { | |
[CmdletBinding()] | |
Param() | |
query user | Select -Skip 1 | ForEach-Object { | |
$_ = $_ -split "\s\s+" | |
$Username = ($_[0].trim(" ")).trim(">") | |
If ($_[1] -match '^\d+$'){ | |
$SessionName = '' | |
$ID = $_[1] | |
$State = $_[2] | |
$IdleTime = $_[3] | |
$LogonDate = $_[4] | |
}Else{ | |
$SessionName = $_[1] | |
$ID = $_[2] | |
$State = $_[3] | |
$IdleTime = $_[4] | |
$LogonDate = $_[5] | |
} | |
$Result = [ordered]@{ | |
Username = $Username | |
SessionName = $SessionName | |
ID = [Int]$ID | |
State = $State | |
IdleTime = $IdleTime | |
LogonDate = [DateTime]::Parse($LogonDate,([Globalization.CultureInfo]::CreateSpecificCulture("$((get-culture).name)"))) | |
} | |
New-Object PSObject -Property $Result | |
} | |
} | |
Function Disconnect-RDPUser { | |
[CmdletBinding(SupportsShouldProcess = $true,ConfirmImpact='High')] | |
Param( | |
[Parameter(ValueFromPipelineByPropertyName=$True)]$ID, | |
[Parameter(ValueFromPipelineByPropertyName=$True)]$Username, | |
$State = "Disc" | |
) | |
$Logoff = $Input | Sort LogonDate | Where {$_.State -eq $State} | |
$Count = ($Logoff).count | |
$i = 0 | |
$Logoff | FT | |
Write-Warning "Logging off $Count users" | |
$Logoff | ForEach-Object { | |
If ($PSCmdlet.ShouldProcess("$($_.username)","Log off")) | |
{ | |
$i ++ | |
Write-Progress -Activity "Logging off $($_.username) from $Env:Computername" -Status "$i of $Count" -PercentComplete (($i/$Count)*100) | |
Logoff $_.ID | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment