0

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 i.e. 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

mklement0
  • 382,024
  • 64
  • 607
  • 775
Traconis
  • 33
  • 1
  • 2
  • 6
  • 2
    It's not a question of changing the WMI class - to find all computers a user might be logged on to, you'll simply need to _query all the computers_ – Mathias R. Jessen May 15 '20 at 12:46
  • Make sense. Do you have any example of how to change the $env: to include all domain's computers, please? – Traconis May 15 '20 at 13:08
  • `$ComputerName = Get-ADComputer -Filter {Enabled -eq $true} |% Name` – Mathias R. Jessen May 15 '20 at 13:24
  • You'll find it far quicker to query the domain controller logs than to query every computer in the domain. If you can give yourself or request read access to the DC security logs then I have a PS forms-based script that will do it for you here : https://github.com/Scepticalist/FindUserLogonLocation – Scepticalist May 15 '20 at 13:51
  • Please take a look [here](https://stackoverflow.com/a/60830666/9898643). You might find the second part of the answer, marked _Experimental_ can be of use to you. – Theo May 16 '20 at 09:19

1 Answers1

0

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"
Vish
  • 466
  • 2
  • 12
  • This one works only for a local machine, i.e. when I parse my username (currently logged in it returns my computer name correctly. If I parse a username not logged onto my local machine it returns nothing. – Traconis May 15 '20 at 13:06