Query User and Machine

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

 

 


            

At a quick glance the code looks fine.

What is the output of $loggedonusers ?

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.

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.