Powershell – Working with Event Logs in Powershell

powershellxml

I have trying to analyze records from the Windows Security log and having a bit of difficulty getting specific values out of some of the logon/logoff events. Let's take a look at a specific example – here's the XML of one of the log entries.

<Event xmlns='http://schemas.microsoft.com/win/2004/08/events/event'>
    <System>
        <Provider Name='Microsoft-Windows-Security-Auditing' Guid='{54849625-5478-4994-a5ba-3e3b0328c30d}'/>
        <EventID>4634</EventID>
        <Version>0</Version>
        <Level>0</Level>
        <Task>12545</Task>
        <Opcode>0</Opcode>
        <Keywords>0x8020000000000000</Keywords>
        <TimeCreated SystemTime='2011-08-16T17:15:38.702857400Z'/>
        <EventRecordID>107947</EventRecordID>
        <Correlation/>
        <Execution ProcessID='680' ThreadID='972'/>
        <Channel>Security</Channel>
        <Computer>SRV1.DOMAIN.LOCAL</Computer><Security/>
    </System>
    <EventData>
        <Data Name='TargetUserSid'>S-1-5-21-963414502-3093649508-813756320-3274</Data>
        <Data Name='TargetUserName'>billgates</Data>
        <Data Name='TargetDomainName'>MYDOMAIN</Data>
        <Data Name='TargetLogonId'>0x1c01acc</Data>
        <Data Name='LogonType'>10</Data>
    </EventData>
</Event>

How would I, for instance, go about extracting the 0x1c01acc stored in the Data node with the Name attribute equal to 'TargetLogonId'?

Best Answer

Make sure your string is valid XML (ie add </Event> to the end of what you've posted above, and then cast that string as XML:

$xml = [xml]$yourStringHere

Then you can pull out the TargetLogonId like this:

$xml.Event.SelectSingleNode("//*[@Name='TargetLogonId']") | select -ExpandProperty '#text'

Thanks to Shay Levy and this post: http://social.technet.microsoft.com/Forums/en/ITCG/thread/5aa133b0-ea69-4348-9bac-d028ba895024