Search code examples
powershellobjectsubstringfilteringevent-viewer

Selecting a sub-property in PowerShell


I have a long list of objects in PowerShell (more specifically, a list of Windows events from the Get-EventLog cmdlet) that I want to filter out to find who accessed my machine. I used the following:

Get-EventLog -LogName Security -InstanceId 4672 | Select-Object -Property TimeGenerated, ReplacementStrings[1]

But the output looks like:

TimeGenerated        ReplacementStrings[1]
-------------        ---------------------
6/17/2018 2:28:33 PM
6/17/2018 2:28:33 PM
6/17/2018 2:28:33 PM
6/17/2018 2:28:33 PM
6/17/2018 2:28:33 PM
...

I have no output at all the right column.

If I remove the [1] from ReplacementString:

TimeGenerated        ReplacementStrings
-------------        ------------------
6/17/2018 2:28:33 PM {S-1-2-3-4, Username1, blablabla...}
6/17/2018 2:28:33 PM {S-1-2-3-4, Username2, blablabla...}
6/17/2018 2:28:33 PM {S-1-2-3-4, Username2, blablabla...}
6/17/2018 2:28:33 PM {S-1-2-3-4, Username1, blablabla...}
6/17/2018 2:28:33 PM {S-1-2-3-4, Username3, blablabla...}
...

I want only the username field from ReplacementStrings.

I could use a foreach loop and manually concentrate to one string, but I want to keep the items as objects for later use, so this is not an option for me.


Solution

  • Use a calculated property:

    Get-WinEvent ... |
      Select-Object -Property TimeGenerated,
                              @{Name='Username'; Expression={$_.ReplacementStrings[1]}}