#PSTip Get last login date for local account

Using the ADSI type accelerator in combination with WinNT provider we can retrieve the last logon time for a local account from the local SAM account database:

1
([ADSI]"WinNT://computer/jaapbrasser").lastlogin

I created a function for this specific purpose to simply get this information from local or remote systems; the function is available in the Microsoft TechNet Script Gallery: Get-LocalLastLogonTime

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
function Get-LocalLastLogonTime {
    param(
    [Parameter(
            Mandatory,
            ValueFromPipeline,
            ValueFromPipelineByPropertyName,
            Position=0
    )]
    [string[]]
        $ComputerName,
    [Parameter(
            Mandatory
    )]
    [string[]]
        $UserName
    )

    begin {
        $SelectSplat = @{
            Property = @('ComputerName','UserName','LastLogin','Error')
        }
    }

    process {
        foreach ($Computer in $ComputerName) {
            if (Test-Connection -ComputerName $Computer -Count 1 -Quiet) {
                foreach ($User in $UserName) {
                    $ObjectSplat = @{
                        ComputerName = $Computer
                        UserName = $User
                        Error = $null
                        LastLogin = $null
                    }
                    $CurrentUser = $null
                    $CurrentUser = try {([ADSI]"WinNT://$computer/$user")} catch {}
                    if ($CurrentUser.Properties.LastLogin) {
                        $ObjectSplat.LastLogin = try {
                                            [datetime](-join $CurrentUser.Properties.LastLogin)
                                        } catch {
                                            -join $CurrentUser.Properties.LastLogin
                                        }
                    } elseif ($CurrentUser.Properties.Name) {
                    } else {
                        $ObjectSplat.Error = 'User not found'
                    }
                    New-Object -TypeName PSCustomObject -Property $ObjectSplat | Select-Object @SelectSplat
                }
            } else {
                $ObjectSplat = @{
                    ComputerName = $Computer
                    Error = 'Ping failed'
                }
                New-Object -TypeName PSCustomObject -Property $ObjectSplat | Select-Object @SelectSplat
            }
        }
    }
} 
Share on: