简体   繁体   中英

Quser with New-Object (Powershell)

My team is currently migrating DHCP to a new Azure server, and when we cutover a particular scope, we manually check if any users are logged in to desktops within the leased IPs before restarting them.

I pieced together 2 scrips to help automate the checking of logged in users. The first successfully retrieves the hostnames for the leased IPs in a particular scope, then exports them to txt.

The second queries the hosts from the results in script 1 using the quser command within a custom object, and that is what I am having troubles with. I thought I'd use New-object to retrieve the users but the results don't look right or seem to be missing data compared to running the quser command manually for each of the servers in question.

Essentially, I am looking for a better way to retrieve logged on users, with the results showing server name, and if a user is logged on, what the user name is (same info as running quser command).


Function Get-File($initialDirectory) {   
 [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
 Out-Null

 $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
 $OpenFileDialog.initialDirectory = $initialDirectory
 $OpenFileDialog.filter = "All files (*.*)| *.*"
 $OpenFileDialog.ShowDialog() | Out-Null
 $OpenFileDialog.filename
}

$scopeservers = Get-File
$servers = Get-Content $scopeservers

foreach ($server in $servers) {$properties = @{
                                               Server = $server
                                               LoggedInUsers = quser /server:$server
                                              } 

                               $o = New-Object psobject -Property $properties; $o
                               }

Alternatively, I tried using Get-CimInstance or Get-WmiObject , but all I got were "RPC SErver Unavailable" errors with those commands.

Any help is greatly appreciated.

Was able to get logged on users using Invoke-Command to run a Scritpblock on the remote machine.

foreach ($server in $servers) {Invoke-Command -ComputerName $server -ScriptBlock {$env:COMPUTERNAME; quser}
                               write-host " "}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM