Advertisement
Guest User

Get-LoggedOn.ps1

a guest
Dec 29th, 2016
3,895
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ## /u/omers - reddit /r/PowerShell
  2.  
  3. <#
  4.     .SYNOPSIS
  5.         List the users that are logged on to a computer or check for a specific user.
  6.  
  7.     .DESCRIPTION
  8.         This function uses the CMD application query.exe to list the users on the local system, a remote system, or a group of remote systems. It converts the query.exe objects.
  9.  
  10.         When using the -CheckFor parameter you are able to check for a specific user and the function will return true/false.
  11.  
  12.     .PARAMETER  Name
  13.         The computer name to be queried.
  14.  
  15.     .PARAMETER  CheckFor
  16.         A specific username to look for.
  17.  
  18.     .EXAMPLE
  19.         PS C:\> Get-LoggedOn
  20.  
  21.         ComputerName Username SessionState SessionType
  22.         ------------ -------- ------------ -----------
  23.         JDOE-Laptop  JohnD    Active       console
  24.  
  25.         - Description -
  26.         In this example without parameters the command returns locally logged in users.
  27.  
  28.     .EXAMPLE
  29.         PS C:\> Get-LoggedOn -Name TERMSERV01
  30.  
  31.         ComputerName Username  SessionState SessionType
  32.         ------------ --------  ------------ -----------
  33.         TERMSERV01   JaneD     Disconnected
  34.         TERMSERV01   JamesR    Disconnected
  35.         TERMSERV01   ToddQ     Active        rdp-tcp
  36.         TERMSERV01   BrianZ    Disconnected
  37.  
  38.         - Description -
  39.         When a computer name is specific you will se a list of users that are connected to that machine.
  40.  
  41.     .EXAMPLE
  42.         PS C:\> Get-LoggedOn -Name TERMSERV01 -CheckFor JaneD
  43.  
  44.         ComputerName IsLoggedOn
  45.         ------------ ----------
  46.         TERMSERV01         True
  47.  
  48.         - Description -
  49.         CheckFor allows you to check for a specific user on a remote machine.
  50.  
  51.     .EXAMPLE
  52.         PS C:\> Get-LoggedOn -Name NONEXISTENT -CheckFor JaneD
  53.  
  54.         ComputerName IsLoggedOn
  55.         ------------ ----------
  56.         NONEXISTENT  [ERROR]
  57.  
  58.         - Description -
  59.         If query.exe cannot access the compute for any reason it will return [ERROR]
  60.  
  61.     .EXAMPLE
  62.         PS C:\> Get-ADComputer -Filter 'name -like "TERMSERV*"' | Get-LoggedOn -CheckFor JaneD
  63.  
  64.         ComputerName   IsLoggedOn
  65.         ------------   ----------
  66.         TERMSERV01          False
  67.         TERMSERV02           True
  68.         TERMSERV03          False
  69.  
  70.         - Description -
  71.         You can pipe a list of computers to check multiple machines at the same time.
  72.  
  73.     .INPUTS
  74.         System.String
  75.  
  76.     .OUTPUTS
  77.         PSCustomObject
  78.  
  79. #>
  80.  
  81. function Get-LoggedOn
  82. {
  83.     [CmdletBinding()]
  84.     [Alias('loggedon')]
  85.     [OutputType([PSCustomObject])]
  86.    
  87.     Param
  88.     (
  89.         # Computer name to check
  90.         [Parameter(ValueFromPipeline = $true,
  91.                    ValueFromPipelineByPropertyName = $true,
  92.                    Position = 0)]
  93.         [Alias('ComputerName')]
  94.         [string]
  95.         $Name = $env:COMPUTERNAME,
  96.        
  97.         # Username to check against logged in users.
  98.         [parameter()]
  99.         [string]
  100.         $CheckFor
  101.     )
  102.    
  103.     Process
  104.     {
  105.         function QueryToObject ($Computer)
  106.         {
  107.             $Output = @()
  108.             $Users = query user /server:$Computer 2>&1
  109.             if ($Users -like "*No User exists*")
  110.             {
  111.                 $Output += [PSCustomObject]@{
  112.                     ComputerName = $Computer
  113.                     Username = $null
  114.                     SessionState = $null
  115.                     SessionType = "[None Found]"
  116.                 }
  117.             }
  118.             elseif ($Users -like "*Error*")
  119.             {
  120.                 $Output += [PSCustomObject]@{
  121.                     ComputerName = $Computer
  122.                     Username = $null
  123.                     SessionState = $null
  124.                     SessionType = "[Error]"
  125.                 }
  126.             }
  127.             else
  128.             {
  129.                 $Users = $Users | ForEach-Object {
  130.                     (($_.trim() -replace ">" -replace "(?m)^([A-Za-z0-9]{3,})\s+(\d{1,2}\s+\w+)", '$1  none  $2' -replace "\s{2,}", "," -replace "none", $null))
  131.                 } | ConvertFrom-Csv
  132.                
  133.                 foreach ($User in $Users)
  134.                 {
  135.                     $Output += [PSCustomObject]@{
  136.                         ComputerName = $Computer
  137.                         Username = $User.USERNAME
  138.                         SessionState = $User.STATE.Replace("Disc", "Disconnected")
  139.                         SessionType = $($User.SESSIONNAME -Replace '#','' -Replace "[0-9]+","")
  140.                     }
  141.                    
  142.                 }
  143.             }
  144.             return $Output | Sort-Object -Property ComputerName
  145.         }
  146.        
  147.         if ($CheckFor)
  148.         {
  149.             $Usernames = @()
  150.             $Sessions = @()
  151.             $Result = @()
  152.             $Users = QueryToObject -Computer $Name
  153.            
  154.             foreach ($User in $Users) {
  155.                 $Usernames += $User.Username
  156.                 $Sessions += $User.SessionType
  157.             }
  158.            
  159.             if ("[Error]" -in $Sessions)
  160.             {
  161.                 $Result += [PSCustomObject]@{
  162.                     ComputerName = $Name
  163.                     IsLoggedOn = "[ERROR]"
  164.                 }
  165.             }
  166.             elseif ($CheckFor -in $Usernames -and "[*]" -notin $Sessions)
  167.             {
  168.                 $Result += [PSCustomObject]@{
  169.                     ComputerName = $Name
  170.                     IsLoggedOn = $true
  171.                 }
  172.             }
  173.             else
  174.             {
  175.                 $Result += [PSCustomObject]@{
  176.                     ComputerName = $Name
  177.                     IsLoggedOn = $false
  178.                 }
  179.             }
  180.             return $Result | select ComputerName,IsLoggedOn
  181.         }
  182.         elseif (!$CheckFor)
  183.         {
  184.             $Result = QueryToObject -Computer $Name
  185.             return $Result
  186.         }
  187.     }
  188.  
  189. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement