Search code examples
powershellactive-directoryevent-viewer

Matching SID from AD and Event Viewer


I'm trying to make a script that searches AD for locked accounts, as well as parses the Security log in Event Viewer and then compare the SID's, and if they match, display information of the user that has the SID.

Import-Module ActiveDirectory
$PDC = "DOMAINCONTROLLER"
$UserInfo = Search-ADAccount -LockedOut
$LockedOutEvents = Get-WinEvent -ComputerName $PDC -FilterHashtable 
@{LogName='Security';Id=4740} | Sort-Object -Property * -Descending
Foreach($Event in $LockedOutEvents){
If($Event.Properties[2] -Match $UserInfo.SID.value)
{
  $Event | Select-Object -Property @(
    @{Label = 'User'; Expression = {$_.Properties[0].Value}}
    @{Label = 'DomainController'; Expression = {$_.MachineName}}
    @{Label = 'EventId'; Expression = {$_.Id}}
    @{Label = 'LockoutTimeStamp'; Expression = {$_.TimeCreated}}
    @{Label = 'Message'; Expression = {$_.Message -split "`r" | Select -First 1}}
    @{Label = 'LockoutSource'; Expression = {$_.Properties[1].Value}}
    )
}}

There seems to be an issue with the arguments in the If statement If($Event.Properties[2] -Match $UserInfo.TargetSID)

The output of $Event.Properties[2] is like this:

 Value                                        
 -----                                        
 S-1-1-1-111111111-111111111-111111111-22222

The output of $UserInfo.SID.Value:

S-1-1-1-111111111-111111111-111111111-11111 S-1-1-1-111111111-111111111-111111111-11111 S-1-1-1-111111111-111111111-111111111-22222 S-1-1-1-111111111-111111111-111111111-11111 S-1-1-1-111111111-111111111-111111111-11111

As you can see one SID is found in both outputs but when matching these two i get "False" as a response. Does anyone have any idea why this happens?

Thank you for your time.


Solution

  • It looks like you're comparing a SecurityIdentifier object to an array of strings (at least that output looks like it's an array - you can use $UserInfo.SID.value.GetType() to make sure). There are two issues with your current code:

    1. The -Match operator only works with two strings, so you can't use that here. But you can use Contains() on the array.
    2. You need to convert the SecurityIdentifier to a string. The Value property does that.

    Try this:

    If ($UserInfo.SID.value.Contains($Event.Properties[2].Value))