forked from stcu/SharedScripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Select-CapturesFromMatches.ps1
50 lines (45 loc) · 1.54 KB
/
Select-CapturesFromMatches.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<#
.SYNOPSIS
Selects named capture group values as note properties from Select-String MatchInfo objects.
.INPUTS
Microsoft.PowerShell.Commands.MatchInfo, output from Select-String that used a pattern
with named capture groups.
.OUTPUTS
System.Management.Automation.PSObject containing selected capture group values.
.EXAMPLE
Select-String '^(?<Name>.*?\b)\s*(?<Email>\S+@\S+)$' addrbook.txt |Select-CapturesFromMatches.ps1
Name Email
---- -----
Arthur Dent adent@example.org
Tricia McMillan trillian@example.com
#>
#Requires -Version 3
[CmdletBinding()][OutputType([psobject])] Param(
# The MatchInfo output from Select-String to select named capture group values from.
[Parameter(Position=0,ValueFromRemainingArguments=$true,ValueFromPipeline=$true)]
[Alias('InputObject')][Microsoft.PowerShell.Commands.MatchInfo]$MatchInfo,
# Return the capture group values without building objects.
[switch] $ValuesOnly
)
Process
{
$value = @{}
if($ValuesOnly)
{
return $MatchInfo.Matches.Groups.Value |select -Skip 1
}
elseif($PSVersionTable.PSEdition -eq 'Desktop' -and $PSVersionTable.CLRVersion -lt [version]4.7)
{ # old CLR is really tedious to get group names
[regex]$regex = $MatchInfo.Pattern
$regex.GetGroupNames() |
where {$_ -Match '\D'} |
foreach {$value.Add($_,$MatchInfo.Matches.Groups[$regex.GroupNumberFromName($_)].Value)}
}
else
{
$MatchInfo.Matches.Groups |
where Name -Match '\D' |
foreach {$value.Add($_.Name,$_.Value)}
}
return [pscustomobject]$value
}