2020 | Scott W. Head  |  Sr. Systems Admin | Certified Microsoft Windows Server Administrator

PowerShell Get Logged on User

<#

    .Synopsis
    Query remote machines to see who is logged on through console session 
    (Not RDP / Not Terminal Serssion)

    .DESCRIPTION
    Gets enabled Windows computers from AD and returns logged in user.

    .EXAMPLE
    Run script on Domain with rights to machines
    Make sure C:\temp folder exists 

#>
  
  # Get List of Server Names from AD
  $MyComputers=Get-ADComputer -Filter {(enabled -eq $True) -and (operatingsystem -like "Windows*")} -Properties * | Select -ExpandProperty Name 
  
  #Instantiate Array
  $MyArray=@()
  $FailedArray=@()
  
  #Check Access to Each Computer
  Foreach($Comp in $MyComputers){
  
      If((Invoke-Command -ErrorAction SilentlyContinue –ComputerName $comp –ScriptBlock {1}) –eq 1){
          $MyArray+=$Comp
      }Else{
          $FailedArray+=$Comp 
      }
  }
  
  #Export Access Check Results
  $FailedArray | Out-File C:\Temp\FailedAccess.txt
  $MyArray | Out-File C:\temp\PassedAccessCheck.txt
  
  #Command on to get logged on user account 
  $MyCommmand={Get-WmiObject -ComputerName localhost -class win32_computersystem | select username}
  
  #Executes Command on Remote Machines 
  Invoke-Command $MyArray -Scriptblock $MyCommmand | Export-Csv C:\temp\ExportedLoggedonUsers.csv -NoTypeInformation