Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Retrieve the Logged on User of a Remote Machine in Powershell

DZone's Guide to

How to Retrieve the Logged on User of a Remote Machine in Powershell

Want to know how to quickly retrieve the logged on user of a remote Windows machine/server? Check out this post.

· DevOps Zone
Free Resource

Download “The DevOps Journey - From Waterfall to Continuous Delivery” to learn about the importance of integrating automated testing into the DevOps workflow, brought to you in partnership with Sauce Labs.

A good way to retrieve users of remote machines could be to filter the process for explorer.exe:

Get-WmiObject -class win32_process -Filter "name = 'Explorer.exe'" -ComputerName MACHINENAME -EA "Stop" | % {$_.GetOwner().User}

For all logged on users though, use the following script: https://gallery.technet.microsoft.com/scriptcenter/d46b1f3b-36a4-4a56-951b-e37815a2df0c

function Get-LoggedOnUser {
#Requires -Version 2.0          
[CmdletBinding()]          
Param            
   (                      
    [Parameter(Mandatory=$true,
               Position=0,                        
               ValueFromPipeline=$true,          
               ValueFromPipelineByPropertyName=$true)]          
    [String[]]$ComputerName
   )#End Param

Begin          
{          
Write-Host "`n Checking Users . . . "
$i = 0          
}#Begin        
Process          
{
    $ComputerName | Foreach-object {
    $Computer = $_
    try
        {
            $processinfo = @(Get-WmiObject -class win32_process -ComputerName $Computer -EA "Stop")
                if ($processinfo)
                {  
                    $processinfo | Foreach-Object {$_.GetOwner().User} |
                    Where-Object {$_ -ne "NETWORK SERVICE" -and $_ -ne "LOCAL SERVICE" -and $_ -ne "SYSTEM"} |
                    Sort-Object -Unique |
                    ForEach-Object { New-Object psobject -Property @{Computer=$Computer;LoggedOn=$_} } |
                    Select-Object Computer,LoggedOn
                }#If
        }
    catch
        {
            "Cannot find any processes running on $computer" | Out-Host
        }
     }#Forech-object(ComputerName)      

}#Process
End
{

}#End

}#Get-LoggedOnUser


Discover how to optimize your DevOps workflows with our cloud-based automated testing infrastructure, brought to you in partnership with Sauce Labs

Topics:
powershell ,script ,remote ,windows

Published at DZone with permission of Merrick Chaffer, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}