Skip to content

Instantly share code, notes, and snippets.

@ByronScottJones
Created March 21, 2021 19:20
Show Gist options
  • Save ByronScottJones/7908ded2228f64a2ae82f2866006fa41 to your computer and use it in GitHub Desktop.
Save ByronScottJones/7908ded2228f64a2ae82f2866006fa41 to your computer and use it in GitHub Desktop.
Select Capture Group and return PSCustomObject
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 {}
}
@ByronScottJones
Copy link
Author

https://www.reddit.com/r/PowerShell/comments/ma2f35/selectcapturegroup_parse_regex_capture_groups_to/

Select-CaptureGroup - Parse Regex capture groups to objects
Script Sharing
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 = "^(?\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d) [(?.+?)] (?.+?): <color #(?\d{6})>(?.*)"

$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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment