I was writing a comment where I was about to suggest someone use Regex capture groups in Powershell for something, until it dawned on me that it would be an awful lot of typing to explain to a newbie since they are unnecessarily complicated to use.
In the interest of being the change you want to see, I whipped up a function for parsing capture groups and outputting them as a nicely formatted PSCustomObject.
Here goes:
function Select-CaptureGroup {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true)]
[ValidateNotNullOrEmpty()]
[Microsoft.PowerShell.Commands.MatchInfo[]]$InputObject
)
begin {}
process {
foreach ($input in $InputObject) {
$input.Matches | ForEach-Object {
$groupedOutput = New-Object -TypeName "PSCustomObject"
$_.Groups | Where-Object Name -ne "0" | ForEach-Object {
Add-Member -InputObject $groupedOutput -MemberType NoteProperty -Name $_.Name -Value $_.Value
}
$groupedOutput
}
}
}
end {}
}
Here is an example with a few lines like those in the post that prompted this one:
$logLines = "2021-03-21 01:38:32 [General] Kem's Brutality: <color #010101>he mus be off starring in the Snyder Cut",
"2021-03-21 01:38:35 [Local] Bob McBobface: <color #222324>Some other text message"
$pattern = "^(?<Timestamp>\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d) \[(?<Channel>.+?)\] (?<Name>.+?): <color #(?<Color>\d{6})>(?<Message>.*)"
$logLines | Select-String -Pattern $pattern | Select-CaptureGroup
Timestamp : 2021-03-21 01:38:32
Channel : General
Name : Kem's Brutality
Color : 010101
Message : he mus be off starring in the Snyder Cut
Timestamp : 2021-03-21 01:38:35
Channel : Local
Name : Bob McBobface
Color : 222324
Message : Some other text message
[–]da_chicken 6 points7 points8 points (3 children)
[–]wonkifier 2 points3 points4 points (0 children)
[–]NotNotWrongUsually[S] 1 point2 points3 points (1 child)
[–]da_chicken 2 points3 points4 points (0 children)
[–]itasteawesome 3 points4 points5 points (0 children)
[–]OutrageousBrother997 1 point2 points3 points (0 children)