Created
July 11, 2019 00:11
-
-
Save amit-g/4253ece643b9c45be5e82e4900b7140e to your computer and use it in GitHub Desktop.
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
# Query Active Directory for computers running a Server operating system | |
$Servers = Get-ADComputer -Filter { OperatingSystem -like "*server*" } | |
# Loop through the list to query each server for login sessions | |
ForEach ($Server in $Servers) { | |
$ServerName = $Server.Name | |
# When running interactively, uncomment the Write-Host line below to show which server is being queried | |
Write-Host "Querying $ServerName" | |
if ((Test-Connection $ServerName -Count 1) 2> $null) { | |
# Run the qwinsta.exe and parse the output | |
$queryResults = (qwinsta /server:$ServerName | ForEach-Object { (($_.trim() -replace "\s+", ",")) } | ConvertFrom-Csv) | |
# Pull the session information from each instance | |
ForEach ($queryResult in $queryResults) { | |
$RDPUser = $queryResult.USERNAME | |
$sessionType = $queryResult.SESSIONNAME | |
# We only want to display where a "person" is logged in. Otherwise unused sessions show up as USERNAME as a number | |
If (($RDPUser -match "[a-z]") -and ($null -ne $RDPUser)) { | |
# When running interactively, uncomment the Write-Host line below to show the output to screen | |
# Write-Host $ServerName logged in by $RDPUser on $sessionType | |
$SessionList = $SessionList + "`n`n" + $ServerName + " logged in by " + $RDPUser + " on " + $sessionType | |
} | |
} | |
} | |
else { | |
Write-Host "$ServerName is not running" | |
} | |
} | |
# When running interactively, uncomment the Write-Host line below to see the full list on screen | |
$SessionList |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment