Search code examples
windowspowershellevent-log

Create variable from Microsoft Security event ID message for Account Name and Caller Computer Name


I am using PowerShell to pull the most recent event ID for a locked out user using the following code:

Get-WinEvent -FilterHashTable @{LogName="Security"; ID=4740} -MaxEvents 1

Then I turn the message into a variable. When I show the message it looks like the screen below. How can I parse the data to create two separate variables. The first variable would be the Account Name and the second variable would be the caller computer name. So I should end up with below

$Account = []
$Caller = [] 

enter image description here


Solution

  • The event-type-specific information of a given log entry is surfaced via the .Properties collection of the EventLogRecord objects returned by Get-WinEvent, which contains values only (no property names), which can be extracted via each element's .Value property

    Therefore, you need to know the indices of the values of interest in order to extract them.

    I infer from the code in this question that indices 0 and 1 refer to the locked-out user's username and the machine on which the lockout occurred, respectively.

    Therefore:

    $evt = Get-WinEvent -FilterHashTable @{LogName="Security"; ID=4740} -MaxEvents 1
    
    $account, $computer = $evt.Properties[0, 1].Value
    

    Note the use of the following techniques:

    • A multi-assigment (multiple target variables on the LHS)
    • PowerShell's support for multiple indices, which returns the targeted elements as an array.
    • Member-access enumeration: the ability to access a property on a collection to have the property values of its elements returned.