Search code examples
powershellget-winevent

Retrieve last logon user and login time of remote computer


I have the following code. I don't see any property of Win-Event that holds the name of the user that logged in except for the "Account Name" in the "Message" property. How can I extract only the "Account Name" part of the "Message" property?

Get-WinEvent -Computer $computer -FilterHashtable @{Logname='Security';ID=4672} -MaxEvents 1 | Select-Object -Property Message

EDIT: I've also tried the following but got an empty string back

Get-WinEvent -Computer $computer -FilterHashtable @{Logname='Security';ID=4672} -MaxEvents 3 | Select @{Name = "Username";Expression = {$_.ReplacementStrings[1]}}

Solution

  • this seems rather roundabout, but it works. there is a Data= option in FilterHashTable, but i can't figure out how to use it. [blush]

    in any case, this searches the .Message property for Account Name and puts the result in the named match property .AccountName.

    $ComputerName = $env:COMPUTERNAME
    
    $GWE_Params = @{
        Computer = $ComputerName
        FilterHashtable = @{
            Logname = 'Security'
            ID = '4672'
            }
        MaxEvents = 3
        }
    
    $EventInfo = @(Get-WinEvent @GWE_Params)
    
    [void]($EventInfo[0].Message -match 'Account Name:\s{1,}(?<AccountName>.+)')
    
    $Matches.AccountName
    

    output ...

    SYSTEM
    

    i presume you will want to filter out accounts like system - that is easily done. [grin]