Show Logged on Users Loop.txt - Notepad

Show Logged on Users Loop

The below PowerShell script reads a list of hostnames and then for each hostname outputs who the logged on user is, if nobody is logged on, or if the hostname is unreachable.

$machines = Get-Content C:\stuff\names.txt 
foreach ($machine in $machines) 
{ 
clear-variable -name fullname, username2, username3, username -force
$username = get-wmiobject -computername $machine.trim()
-class win32_computersystem -property username
|
select-object -expandproperty username | out-string $username2=$username.trimend() $username3=$username2.remove(0,15) $fullname = Get-ADUser -Identity $username3 -property displayname | Select-Object
-expandproperty displayname | out-string if ($username -eq [string]::Empty) { "{0},{1},{2}" -f (get-date),$machine, "[Unreachable]" | add-content -path
c:\stuff\computers.csv
} elseif ($username -eq $null) { "{0},{1},{2}" -f (get-date),$machine, "[Nobody logged on]" | add-content -path
c:\stuff\computers.csv
} else { "{0},{1},{2}" -f (get-date),$machine,$fullname.trimend() | add-content -path
c:\stuff\computers.csv
} }

Back