loading...

Discussion on: Regex isn't that hard

dinmon profile image
Dinys Monvoisin Author

Oh, using a string itself in PowerShell. Interesting. May I have more context about the application of it?

Thread Thread
cmohan profile image
Catherine Mohan

Sure! One of the recent times I've used regular expressions is when I needed to search the Windows Event Logs. In the GUI, you can only reliably search by Event ID even though the actual event has lots of info. You can get that info with the Get-EventLog Powershell command. It's all in the Message property, but that property is just a very long string even if it looks like this:

Computer: comp-01
User: catherine.mohan
CreationTime: 9/12/2020 9:31:00 PM

Since I can't save it to a variable and access it like $var.User as you would expect, I have to do this instead to get the User value.

$matches = $event.Message | Select-String -Pattern "User: (.*?)\n"
$matches.Matches.Groups[1]

# Output: catherine.mohan

If I need the same info from a lot of results, I will make arrays of my own custom objects so I only have to do the matching process once in a loop. Now that I can get the values, I can use them to filter the results and search for the events I need with greater accuracy.

Thread Thread
dinmon profile image
Dinys Monvoisin Author

Wow, that's so cool. I did not know that you could access EventLog through PowerShell. Thanks for sharing. I will try to explore interesting stuff you can do with PowerShell when I have time.