Created
          April 18, 2017 19:02 
        
      - 
      
- 
        Save Kreloc/52734ffec3253e61e7f7796b32924dc8 to your computer and use it in GitHub Desktop. 
    Get the active user using explorer.exe
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | Function Get-akActiveUser | |
| { | |
| <# | |
| .SYNOPSIS | |
| This function gets the activer user on specified computer. | |
| .DESCRIPTION | |
| This function gets the activer user on specified computer as defined by the running explorer process on their system. Potentially may return | |
| more than one user. | |
| .PARAMETER ComputerName | |
| The name of the computer to be used to determine the active user. | |
| .EXAMPLE | |
| Get-ActiveUser | |
| Get the active user(s) for the computer running PowerShell. | |
| .EXAMPLE | |
| Get-Content computers.txt | Get-ActiverUser | |
| Get the active user(s) for each computer on each line in the text file computers.txt | |
| .EXAMPLE | |
| Get-ADComputer -SearchBase "OU=SomeWhere,DC=contonso,DC=com" | Select -ExpandProperty Name | Get-akActiveUser | |
| Gets the active user(s) for each computer under the SomeWhere OU in ActiveDirectory. | |
| #> | |
| [CmdletBinding()] | |
| param | |
| ( | |
| [Parameter(Mandatory=$False, | |
| ValueFromPipeline=$True, ValueFromPipelinebyPropertyName=$true)][Alias('Name')] | |
| [string[]]$ComputerName = $env:COMPUTERNAME | |
| ) | |
| Begin{} | |
| Process | |
| { | |
| ForEach($Computer in $ComputerName) | |
| { | |
| Write-Verbose "Connecting to WMI on $Computer" | |
| Try | |
| { | |
| $Processes = Get-WmiObject -class win32_process -ComputerName $Computer -filter "ExecutablePath like '%explorer.exe'" -ErrorAction Stop | |
| } | |
| Catch | |
| { | |
| Write-Error -Message "Could not connect to WMI Class Win32_Process on $Computer" | |
| Continue | |
| } | |
| $uid = @($Processes | Foreach-Object {$_.GetOwner().User} | Where-Object {$_ -ne "NETWORK SERVICE" -and $_ -ne "LOCAL SERVICE" -and $_ -ne "SYSTEM"} | Sort-Object -Unique) | |
| If($uid -like "") | |
| { | |
| $props = @{ActiveUser="NA" | |
| ComputerName=$Computer | |
| } | |
| } | |
| else | |
| { | |
| $uid = ($uid | Out-String).TrimEnd() | |
| $props = @{ActiveUser=$uid | |
| ComputerName=$Computer | |
| } | |
| } | |
| New-Object -TypeName Psobject -Property $props | |
| } | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment