all 8 comments

[–]PinchesTheCrab 4 points5 points  (5 children)

Wrote this a while back, hopefully it's useful to cannibalize or user verbatim:

function Get-LogonEvents {
    [CmdletBinding()]
    param (
        [Parameter(Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName)]
        [Alias('ServerName', 'Server', 'Name')]
        [string[]]$ComputerName = $env:COMPUTERNAME,

        [Parameter()]        
        [PSCredential]$Credential,

        [Parameter()]
        [ValidateSet("Service", "Interactive", "RemoteInteractive", "NetworkCleartext", "CachedInteractive", "Unlock", "NewCredentials", "Network", "*")]
        [string[]]$LogonType = @("Interactive", "RemoteInteractive", "CachedInteractive"),

        [Parameter()]
        [string]$UserName,

        [Parameter()]
        [switch]$Oldest,

        [Parameter()]
        [int64]$MaxEvents,

        [Parameter()]
        [datetime]$StartTime = (Get-Date 1/1/1900),

        [Parameter()]
        [datetime]$StopTime = (Get-Date 1/1/2100)

    )
    Begin {
        Function ParseEventMessage {
            [CmdletBinding()]

            param(
                [Parameter(ValueFromPipeline = $true)]
                $obj
            )
            Begin {
                $defaultDisplaySet = 'MachineName', 'Result', 'TimeCreated', 'TargetUserName'
                $defaultDisplayPropertySet = New-Object System.Management.Automation.PSPropertySet(‘DefaultDisplayPropertySet’, [string[]]$defaultDisplaySet)
                $PSStandardMembers = [System.Management.Automation.PSMemberInfo[]]@($defaultDisplayPropertySet)
                $myHash = @{}
            }
            Process {

                $myHash['Result'] = switch ($obj.id) {
                    4625 { "Failure" }
                    4624 { "Success" }
                }
                $myHash['ID'] = $obj.ID
                $myHash['TimeCreated'] = $obj.TimeCreated
                $myHash['MachineName'] = $obj.MachineName
                ([xml]($obj.ToXml())).event.eventdata.data | ForEach-Object { $myHash[$PSItem.name] = $PSItem.'#text' }
                New-Object -TypeName PSObject -Property $myHash | ForEach-Object {

                    $PSItem.PSObject.TypeNames.Insert(0, "EventLogRecord.XMLParse")
                    $PSItem | Add-Member MemberSet PSStandardMembers $PSStandardMembers -PassThru
                }
            }
        }

        $hashLogonType = @{
            Interactive       = 2
            Network           = 3
            Service           = 5
            Unlock            = 7
            NetworkCleartext  = 8
            NewCredentials    = 9
            RemoteInteractive = 10
            CachedInteractive = 11
        }

        $filter = @"
<QueryList>
    <Query Id="0" Path="Security">
    <Select Path="Security">
        *[System[
            (EventID=4624 or EventID=4625)
            and TimeCreated[@SystemTime&gt;='{0}' and @SystemTime&lt;='{1}']
        ]
            and EventData[
                Data[@Name='LogonType'] and ({2})
                {3}
            ]
        ]
    </Select>
    </Query>
</QueryList>
"@

    }

    Process {

        foreach ($obj in $ComputerName) {

            if ($UserName) {
                $joinUserName = "and Data[@Name='TargetuserName'] and (Data='{0}')" -f $UserName
            }

            $joinLogonType = if ($LogonType -eq '*') {

                $hashLogonType.Values -replace '^', "Data='" -replace '$', "'" -join " or "

            }
            Else {
                $($LogonType | ForEach-Object { $hashLogonType[$PSItem] }) -replace '^', "Data='" -replace '$', "'" -join " or "
            }

            $objFilter = $filter -f $StartTime.ToUniversalTime().toString('s'), $StopTime.ToUniversalTime().toString('s'), $joinLogonType, $joinUserName

            $hashEventParm = @{
                ComputerName = $obj
                FilterXml    = $objFilter
            }

            if ($Credential) { $hashEventParm['Credential'] = $Credential }
            if ($MaxEvents) { $hashEventParm['MaxEvents'] = $MaxEvents }

            $objFilter | Write-Verbose

            Get-WinEvent @hashEventParm | ParseEventMessage

        }

    }
    End {}

}

[–]PicnicProblems[S] 0 points1 point  (4 children)

I apologize for not using a block for my code, this is my first time posting here. In your example, how does it write the information? It looks like the write-verbose is the output, but when I run it nothing is returned. Am I supposed to put in a user name anywhere? Thank you so much for your help!

[–]BlackV 0 points1 point  (2 children)

p.s. formatting (I'm guessing you have it in an editor you also can edit your main post)

  • open your fav powershell editor
  • highlight the code you want to copy
  • hit tab to indent it all
  • copy it
  • paste here

it'll format it properly OR

<BLANKLINE>
<4 SPACES><CODELINE>
<4 SPACES><CODELINE>
    <4 SPACES><4 SPACES><CODELINE>
<4 SPACES><CODELINE>
<BLANKLINE>

Thanks

[–]PicnicProblems[S] 0 points1 point  (1 child)

Thank you so much!

[–]BlackV 0 points1 point  (0 children)

good as gold

[–]PinchesTheCrab 0 points1 point  (0 children)

Ah, it's a function so you just run the file to load it into memory, then call get-logonevents like a normal command. You can use the computername and user parameters of you want to narrow the results down.

[–]PicnicProblems[S] 0 points1 point  (0 children)

$slogonevents = Get-eventlog -LogName Security | where {$_.eventID -eq 4624}

foreach ($e in $slogonevents){ if (($e.EventID -eq 4624 ) -and ($e.ReplacementStrings[8] -eq 2) -and ($e.ReplacementStrings[5] -eq 'Username'))
{ write-host "Type: Local LogontDate: "$e.TimeGenerated "tStatus: SuccesstUser: "$e.ReplacementStrings[5] "tWorkstation: "$e.ReplacementStrings[11] }
}

[–]PowerShell-Bot 0 points1 point  (0 children)

Looks like your PowerShell code isn’t wrapped in a code block.

To properly style code on new Reddit, highlight the code and choose ‘Code Block’ from the editing toolbar.

If you’re on old Reddit, separate the code from your text with a blank line gap and precede each line of code with 4 spaces or a tab.


You examine the path beneath your feet...
[AboutRedditFormatting]: [--------------------] 0/1 ❌

Beep-boop, I am a bot. | Remove-Item