2
\$\begingroup\$

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?

asked Mar 27, 2018 at 12:46
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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
answered Apr 7, 2018 at 1:03
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.