I'm trying to find out which terminal server a user is connected to. Currently I'm trying to cycle through each server and check if he is connected.
$servers = @("server01","server02","server03","server04","server05","server06","server07","server08")
foreach ($server in $servers ) {
$WMI = Get-WmiObject -Class Win32_Process -ComputerName $server -ErrorAction Stop
$ProcessUsers = $WMI.getowner().user | Select-Object -Unique
if ( $ProcessUsers.Contains("user")) {
$userServer = $server
break
}
}
echo $userServer
This can take some time depending on the server the user is connected too. Is there any better way to check this with PowerShell?
1 Answer 1
A couple things here... I would use the Win32_LoggedOnUser class to query, that'll get you the user name and "domain" for anybody with a connection to the computer. I have quotes on domain, because it considers the computer itself to be the domain for any local accounts. You just have to do a little string parsing to get the info you want into a nice, readable format.
Get-WmiObject -Class Win32_LoggedOnUser -ComputerName 'Server01' |
Select PSComputerName,@{l='Domain';e={$_.Antecedent -replace '^.+?Domain="(.+?)".*$','1ドル'}},@{l='Name';e={$_.Antecedent -replace '^.+?Name="(.+?)".*$','1ドル'}} -Unique
Then, you can pass multiple computer names to the Get-WmiObject cmdlet at once, and it'll get the info from all of them. Plus, if you run it as a background job you can set a throttle limit, and it will try to process as many connections as you set the limit to.
$servers = @("server01","server02","server03","server04","server05","server06","server07","server08")
$Job = Get-WmiObject Win32_LoggedOnUser -ComputerName $servers -AsJob -ThrottleLimit 10
Wait-Job $Job
$Results = Receive-Job $Job
$Results | Select PSComputerName,@{l='Domain';e={$_.Antecedent -replace '^.+?Domain="(.+?)".*$','1ドル'}},@{l='Name';e={$_.Antecedent -replace '^.+?Name="(.+?)".*$','1ドル'}} -Unique | Sort PSComputerName,Domain,Name