Last active
July 25, 2023 23:12
-
-
Save IISResetMe/654b302383a687bd92faa8c8c3ab28fa to your computer and use it in GitHub Desktop.
Quick and dirty regex-based text-to-object parsing using named expressions groups and $Matches
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ConvertTo-Object { | |
param( | |
[Parameter(Mandatory=$true,ValueFromPipeline=$true)] | |
[AllowEmptyString()] | |
[string[]]$InputString, | |
[Parameter(Mandatory=$true,ValueFromRemainingArguments=$true)] | |
[string[]]$Pattern | |
) | |
process{ | |
foreach($string in $InputString |?{$_}){ | |
foreach($p in $Pattern){ | |
if($string -match $p){ | |
if($PropertyNames = $Matches.Keys |Where-Object {$_ -is [string]}){ | |
$Properties = $PropertyNames |ForEach-Object -Begin {$t = @{}} -Process {$t[$_] = $Matches[$_]} -End {$t} | |
[PSCustomObject]$Properties | |
} | |
break | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment