Friday, 2 September 2016

How to retrieve the logged on user of a remote machine in powershell

Note: For windows 7 desktop users you’ll need to install the active directory modules for powershell by following the installation steps here
https://www.microsoft.com/en-gb/download/details.aspx?id=7887

A better version could be to filter the process for explorer.exe

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

Or if you wish to resolve down to the actual full person's name

Get-WmiObject -class win32_process -Filter "name = 'Explorer.exe'" -ComputerName WDUKLON-0102 -EA "Stop" | % {Get-AdUser -Identity $_.GetOwner().User | Select -Property Name}

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

No comments:

Post a Comment

How to fix blurry images in Google Chrome

Problem When browsing sites with thumbnail images, those images appear blurred in Chrome, but not in other browsers such as Internet Explore...