85xlt
September 4, 2020, 10:55am
1
Hello,
I hope this is the right place to write my question.
I want to search all my domain computers for the currently logged on user.
I have this command:
Get-WMIObject -Class Win32_ComputerSystem -ComputerName (Get-Content C:\Temp\ComputerNames.txt) | Select Name, Username
It works great, but I want to it to skip computers that don’t reply, turned off or out of the office (in the case of laptops).
How would I do that?
Thank you,
There are many scripts for getting logged on users. Have you tried to search “Powershell Get Logged On User”? If you want to write it yourself, you can minimally use the scripts as a guide as they will have logic to test connections.
Check out Test-Connection .
You could do something like the following. However, this will be slow for a lot of computers.
$ConnectedComps = Test-Connection -ComputerName (Get-Content C:\Temp\ComputerNames.txt) -Count 1 | Select -Expand Address -Unique
This type of task is better suited for a configuration/inventory management solution.
Please try the below code:
$Today = Get-Date -Format 'F'
$SessionList = "n
nRDP Session List - " + $Today + "n
n"
$CurrentSN = 0
$Servers = Get-Content C:\Temp\ComputerNames.txt
$NumberOfServers = $Servers.Count
# Iterate through the retrieved list to check RDP sessions on each machine
ForEach ($Server in $Servers)
{
Write-Host "Processing $Server ..." -ForegroundColor Yellow
Write-progress -activity "Checking RDP Sessions" -status "Querying $Server" -percentcomplete (($CurrentSN / $NumberOfServers) * 100)
try
{
$SessionList += qwinsta /server:$Server |
Select-Object -Skip 1 |
% {
[PSCustomObject] @{
Type = $_.Substring(1, 18).Trim()
User = $_.Substring(19, 20).Trim()
ID = $_.Substring(41, 5).Trim()
State = $_.Substring(48, 6).Trim()
}
} |
? { $_.Type -notin 'console', 'services', 'rdp-tcp' -and $_.User -ne $null -and $_.User -ne 65536 } |
% {
[PSCustomObject] @{
Server = $Server
User = $_.User
LogonType = $_.Type
ID = $_.ID
State = $_.State
}
"`n$Server logged in by $($_.User) on $($_.Type), session id $($_.ID) $($_.state)"
}
}
catch
{
$SessionList += "`n Unable to query " + $Server
write-host "Unable to query $Server! `n $($Error[0].Exception)" -foregroundcolor Red
}
$CurrentSN++
}
# Send the output the screen.
$SessionList + "n
n"
$sendMailArgs = @{
From = "$env:USERNAME@$env:userdnsdomain"
To = 'YourEmail@domain.com'
SmtpServer = 'SMTP.domain.com'
Priority = 'High'
Body = $SessionList | Select-Object Server, User, LogonType, ID, State
Subject = "$($SessionList.Count) Logged On users from $($NumberOfServers) online servers as at $($Today)"
}
Send-MailMessage @sendMailArgs
Hope that helps.