PoshCode Archive  Artifact [9fcbb2fcfb]

Artifact 9fcbb2fcfb8be7dac46f5431e4620c6acf918c9431a81fa948339288f3af50b9:

  • File Get-LastLoggedOnUser.ps1 — part of check-in [1a6731dd86] at 2018-06-10 14:06:09 on branch trunk — Gets the last logged on user of a workstation. (user: dotps1 size: 1395)

# 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 {}
}