Public/Get-WinLogedOnUser.ps1

Function Get-WinLogedOnUser{
    <#
        .SYNOPSIS
        Return a list of logged in users
 
        .DESCRIPTION
        This function return a list of users, who have logged in to the target computer.
        Logic of this function is based on 'Explorer.exe' process. It finds the processes and return the owner of those.
        If do not define computer name, localhost will be choose as a target computer
 
        .EXAMPLE
        PS> Get-WinLogedOnUser
 
        Name Domain Computer
        ---- ------ --------
        User01 Contoso PC-01
 
        .EXAMPLE
        PS> Get-WinLogedOnUser -ComputerName PC-02
 
        Name Domain Computer
        ---- ------ --------
        User02 Contoso PC-02
 
        .EXAMPLE
        PS> $list = 'PC-01','PC-02'
        PS> $list | Get-WinLogedOnUser
 
        Name Domain Computer
        ---- ------ --------
        User01 Contoso PC-01
        User02 Contoso PC-02
    #>

    [CmdletBinding()]
    [OutputType([Parmis.Windows.LoginUser])]
    Param (
        [Parameter(ValueFromPipeline=$true)]
        [string]$ComputerName
    )

    begin{
        if ([string]::IsNullOrEmpty($ComputerName)){
            $ComputerName = $env:COMPUTERNAME
        }

        [Parmis.Windows.LoginUser[]]$output = @()

    }
    Process{
        Write-Verbose -Message ("========== {0} ==========" -f $ComputerName)
        $testResult = Test-NetConnection -ComputerName $ComputerName -InformationLevel Quiet
        if ($testResult){
            $procs = Get-CimInstance -ComputerName $ComputerName  Win32_Process -Filter "name = 'Explorer.exe'"
            foreach ( $item in $procs){
                $owner = Invoke-CimMethod -ComputerName $ComputerName -InputObject $item -MethodName GetOwner
                $obj = [Parmis.Windows.LoginUser]::new()

                $obj.Name = $owner.User
                $obj.Domain = $owner.Domain
                $obj.Computer = $ComputerName

                $output += $obj
            }
        }
    }
    End{
        return $output | Select-Object Name,Domain,Computer -Unique | Sort-Object -Property Computer,Name
    }
}