Get-LastLoggedOnUser.ps1


<#PSScriptInfo
 
.VERSION 1.0.0.1
 
.GUID f994a5fb-c978-4e1a-b549-e64c3fab097b
 
.AUTHOR Thomas Malkewitz @dotps1
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS
 
.LICENSEURI
 
.PROJECTURI https://dotsp1.github.io/Functions
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES changed error handling.
 
 
#>


<#
 
.DESCRIPTION
 Gets the last logged on user.
 
#>


[CmdletBinding()]
[OutputType(
    [PSCustomObject]
)]

Param(
    [Parameter(
        ValueFromPipeline = $true,
        ValueFromPipelineByPropertyName = $true
    )]
    [ValidateScript({
        if (Test-Connection -ComputerName $_ -Count1 -ErrorAction SilentlyContinue) {
            $true
        } else {
            throw "Unable to contact $_."
        }
    })]   
    [Alias(
        "ComputerName"
    )]
    [String[]]
    $Name = $env:COMPUTERNAME,

    [Parameter(
        ValueFromPipelineByPropertyname = $true
    )]
    [ValidateNotNull()]
    [System.Management.Automation.PSCredential]
    [System.Management.Automation.Credential()]
    $Credential
)

Process {
    foreach ($item in $Name) {
        $params = @{
            Class = "Win32_UserProfile"
            Namespace = "root\CimV2"
            ComputerName = $item
            ErrorAction = "Stop"
        }

        if ($PSBoundParameters.ContainsKey("Credential")) {
            $params.Add(
                "Credential", $Credential
            )
        }

        try {
           Get-WmiObject @params |
                Sort-Object -Property LastUseTime |
                    ForEach-Object {
                        if (-not($_.Special) -and ($null -ne $_.LastUseTime)) {
                            [PSCustomObject]@{
                                UserName = ([System.Security.Principal.SecurityIdentifier]$_.SID).Translate(
                                    [System.Security.Principal.NTAccount]
                                ).Value
                                SID = $_.SID
                                LastLoggedOnTimeStamp = $_.ConvertToDateTime($_.LastUseTime)
                                CurrentlyLoggedOn = $_.Loaded
                            }
                        }
                    } -ErrorAction Stop |
                        Select-Object -Last 1
        } catch {
            Write-Error -Message $_.ToString()

            continue
        }
    }
}