Click an Ad

If you find this blog helpful, please support me by clicking an ad!

Thursday, February 27, 2014

Remotely Find What User is Logged In - Put This in Your Profile!

It was occurring quite often that I would attempt to shut down or reboot a system only to find that "other users" were logged in. So I found the function below on the internet and adapted it a bit, I guess, because I removed the attribution info. So if this is yours, I'm sorry for not crediting you.

If you find it useful, I would recommend adding it to your profile so it loads the function every time you open Powershell. Do this by pasting it into C:\Users\username\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1.

Syntax is Get-LoggedOnUser <ComputerName>

#---------------------BEGIN SCRIPT---------------------------

#This loads the function into your session so you can use Get-LoggedOnUser "Servername"

function global: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

#--------------------------END SCRIPT------------------------

2 comments:

  1. Pretty slick and useful.

    I modified it a bit as I have several domains in my environment.

    Tacked on "-Impersonation 3 -Credential Domain\Administrator" after win32_process and before -ComputerName

    Thanks!

    ReplyDelete
  2. That's a good addition, thanks for sharing!

    ReplyDelete