Query User and Machine

Welcome Forums General PowerShell Q&A Query User and Machine

This topic contains 3 replies, has 4 voices, and was last updated by

 
Participant
1 month ago.

  • Author
    Posts
  • #112162

    Participant
    Points: 0
    Rank: Member

    Hi

    I am hoping someone can help with this code.
    The purpose of this script is to query and write out to a csv,  the output of what user and machine is logged on to the network from VNCMachines.txt

    I'd like to write in one column the user and then in the other the machine

    I suspect csv cannot render this data correctly.

    I hope this makes sense.
    Apologies in advance if I've pasted the code in wrong

    Many thanks

    $MachineList = Get-Content -Path C:\scripts\VNCMachines.txt; # One system name per line
    
    $LoggedOnUsers = foreach ($Machine in $MachineList) {
        if (Test-Connection -ComputerName $Machine -Quiet -Count 1) {
            $UserNames = (Get-WmiObject -ComputerName $Machine -Namespace root\cimv2 -Class Win32_ComputerSystem).UserName
            foreach ($UserName in $UserNames) {
                [PSCustomObject]@{
                    UserName = $UserName
                    Machine  = $Machine
                }
            }
        }
    }
    
    $LoggedOnUsers | Export-Csv -Path C:\scripts\VNCMachinesLoggedOnUsers.csv -NoTypeInformation

     

     

    
    
    		
  • #112192
    Jon

    Participant
    Points: 2
    Rank: Member

    At a quick glance the code looks fine.

    What is the output of $loggedonusers ?

  • #112201

    Participant
    Points: 5
    Rank: Member

    I'm guessing that you try to check users on virtual machines and have issues getting the username?

    If so then the above code won't work since the users are not really logged on interactively.
    They are in a e.g. RDP-session.

    A work around is to check for the process owners for e.g. explorer.exe
    If you google around you'll find examples on how to check for that.

  • #112202

    Participant
    Points: 65
    Published
    Rank: Member

    I don't think, there will be multiple usernames will come from this instance.

    $MachineList = Get-Content -Path C:\scripts\VNCMachines.txt
    
    $LoggedOnUsers = foreach ($Machine in $MachineList) {
        if (Test-Connection -ComputerName $Machine -Quiet -Count 1) {
            $UserNames = (Get-WmiObject -ComputerName $Machine -Namespace root\cimv2 -Class Win32_ComputerSystem | Select-Object -Property Username,PSComputerName
           }
        }
    }
    
    $LoggedOnUsers | Export-Csv -Path C:\scripts\VNCMachinesLoggedOnUsers.csv -NoTypeInformation
    

    PS: Make sure no trailing or leading spaces are there in the machines list.

You must be logged in to reply to this topic.