# encoding: ascii
# api: powershell
# title: Get-LastLoggedOnUser
# description: Gets the last logged on user of a workstation.
# version: 0.1
# type: function
# author: dotps1
# license: CC0
# function: Get-LastLoggedOnUser
# x-poshcode-id: 6018
# x-archived: 2015-09-20T03:30:23
# x-published: 2015-09-18T19:20:00
#
#
#requires -RunAsAdministrator

Function Get-LastLoggedOnUser {
    
    [OutputType([PSCustomObject])]

    Param (
        [Parameter(
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName = $true
        )]
        [Alias('ComputerName')]
        [String[]]
        $Name = $env:COMPUTERNAME
    )

    Begin {}

    Process {
        foreach ($n in $Name) {
            Get-WmiObject -Class Win32_UserProfile -Namespace 'root\CimV2' -ComputerName $n -ErrorAction Stop | Sort-Object -Property LastUseTime | ForEach-Object {
                if (-not ($_.Special)) {
                    [PSCustomObject]@{
                        UserName = ([System.Security.Principal.SecurityIdentifier]$_.SID).Translate([System.Security.Principal.NTAccount]).Value
                        LastLoggedOnTimeStamp = $_.ConvertToDateTime($_.LastUseTime)
                        CurrentlyLoggedOn = $_.Loaded
                    }
                }
            } | Select-Object -Last 1
        }
    }

    End {}
}
