PowerShell: Script to get local loggedon user information

by Sitaram Pamarthi on August 12, 2011

Querying the user lists who interactively logged on to a computer. I want to do this from very long time using powershell so that I can use it in my other powershell scripts. Earlier I tried to do it via WMI but I was not very successful. After struggling for some time, I finally made a code which works for most windows platforms from which you can query interactively logged on users information.

This script is a wrapper which depends on most famous psloggedon utility. It parses the output of the psloggedon util and prepares a object with domain and user information.

function Get-LoggedOnUsers {            

[cmdletbinding()]            
param(            

[parameter(valuefrompipelinebypropertyname=$true)]            
[string]$ComputerName = $env:computername            

)            

begin {}            
process {            

[object[]]$sessions = Invoke-Expression "PsLoggedon.exe -x -l \$ComputerName 2> null" |             
        Where-Object {$_ -match '^s{2,}((?w+)\(?S+))'} |             
        Select-Object @{             
            Name='Computer'             
            Expression={$ComputerName}             
        },             
        @{             
            Name='Domain'             
            Expression={$matches.Domain}             
        },             
        @{             
            Name='User'             
            Expression={$Matches.User}             
        }             

    IF ($Sessions.count -ge 1)             
    {             
        return $sessions            
    }             
    Else             
    {             
        'No user logins found'            
    }             

}            
end {}            
}

I found this code originally at Scripting Guys blog. I had to make few modifications to make it parse the output properly and exclude the psloggedon util logo information.

This post was written by...

– who has written 463 posts on Techibee.com.

Sitaram Pamarthi is a windows administrators with 9+ years of experience.read more

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: