Oneliner: Get Logged on Users with Powershell

Check out this oneliner/function! Provide a computer name and it will return the logged on users.

function Get-MyLoggedOnUsers
{
 param([string]$Computer)
¬†Get-WmiObject Win32_LoggedOnUser -ComputerName $Computer | Select Antecedent -Unique | %{“{0}{1}” -f $_.Antecedent.ToString().Split(‘”‘)[1], $_.Antecedent.ToString().Split(‘”‘)[3]}
}

Hugo

8 thoughts on “Oneliner: Get Logged on Users with Powershell”

  1. Hugo,

    your script is almost working :-)

    can only give me the following result:

    Laptop425SYSTEM
    Laptop425LOCAL SERVICE
    Laptop425NETWORK SERVICE
    MYDOMAINusername
    Laptop425ANONYMOUS LOGON

    how to get MYDOMAIN\username only ?

  2. I’ve just made a little change in the script to add the computername.
    You can now use it with a server list as well as a single server.


    function Get-MyLoggedOnUsers
    {
    param([Array]$Computer)
    Get-WmiObject Win32_LoggedOnUser -ComputerName $Computer |
    Select __SERVER, Antecedent -Unique |
    %{"{0} : {1}\{2}" -f $_.__SERVER, $_.Antecedent.ToString().Split('"')[1], $_.Antecedent.ToString().Split('"')[3]}
    }


    Get-MyLoggedOnUsers localhost

    or

    Get-MyLoggedOnUsers Server1

    or

    $Server_List = ("Server1","Server2","Server3")
    Get-MyLoggedOnUsers $Server_List

  3. Yours, combined with
    http://learn-powershell.net/2010/11/01/quick-hit-find-currently-logged-on-users/
    and
    http://forums.techarena.in/software-development/1118294.htm

    function get-loggedonusers
    {
    param([Array]$Computer)
    $computers = get-wmiobject Win32_Computersystem -computername $Computer
    $report = @()
    foreach ($c in $computers) {
    $temp = "" | Select Computer, Username
    $temp.Computer = $c.name
    $temp.Username = $c.username
    $report += $temp
    }#foreach
    $report
    }#function

    Dump anything else from http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102(v=vs.85).aspx in there if needed.

    Thanks for your method.

  4. To output the current username by itself, use:

    function Get-LoggedOnUsers {
    $Computers = HOSTNAME
    $Computers | foreach {$((Get-WmiObject Win32_ComputerSystem | Select UserName | Format-Table -HideTableHeaders | Out-String) -split ‘\\’)[1]}
    }

    Get-LoggedOnUsers

    To output the username as DOMAIN\username, use:

    function Get-LoggedOnUsers {
    $Computers = HOSTNAME
    $Computers | foreach {$(Get-WmiObject Win32_ComputerSystem | Select UserName | Format-Table -HideTableHeaders | Out-String)}
    }

    Get-LoggedOnUsers

    Hope this helps

  5. I run this locally and I get the user just fine. But if I put in a remote computer, I just get a blank. Are there any security settings to be aware of while running this? I run the script as an Admin of the remote computers as well.
    Thanks,
    –S

Leave a Reply