简体   繁体   中英

PowerShell to find computers in the domain, user is logged on

I am fairly new to PowerShell. I have this script working for computer names on the domain, thanks to @Adam Bertram https://4sysops.com/archives/how-to-find-a-logged-in-user-remotely-using-powershell/ . I understand it and it works fine on my domain ie I can query the computer name and it returns a list of logged users. I have difficulties altering the code so it could return a list of computer names for a given user, instead. I believe the issue could be with the correct Win32 class.

function Get-LoggedOnUser
 {
     [CmdletBinding()]
     param
     (
         [Parameter()]
         [ValidateScript({ Test-Connection -ComputerName $_ -Quiet -Count 1 })]
         [ValidateNotNullOrEmpty()]
         [string[]]$ComputerName = $env:COMPUTERNAME
     )
     foreach ($comp in $ComputerName)
     {
         $output = @{ 'ComputerName' = $comp }
         $output.UserName = (Get-WmiObject -Class win32_computersystem -ComputerName $comp).UserName
         [PSCustomObject]$output
     }
 }

thanks Tomasz

Try this:

function Get-LoggedOnUser
 {
     [CmdletBinding()]
     param
     (
         [ Parameter() ]
         $UserName
     )

     Get-WmiObject -Class win32_computersystem | Where-Object { $_.Username -like  "*$UserName*" } | Select-Object Name
 }

 Get-LoggedOnUser -UserName "vish"

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