Last active
October 8, 2021 10:20
-
-
Save indented-automation/4034593752a05c6c098e1d5d7dd14073 to your computer and use it in GitHub Desktop.
A quick replacement for ConvertFrom-StringData which supports ordered dictionary output
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 ConvertFrom-StringData { | |
<# | |
.FORWARDHELPTARGETNAME Microsoft.PowerShell.Utility\ConvertFrom-StringData | |
#> | |
[CmdletBinding()] | |
param ( | |
[Parameter(Mandatory, Position = 1, ValueFromPipeline)] | |
[string]$StringData, | |
[char]$Delimiter = '=', | |
# Create an ordered dictionary instead of a hashtable. | |
[switch]$Ordered | |
) | |
begin { | |
$splitPattern = '\s*{0}\s*' -f ([Regex]::Escape($Delimiter)) | |
} | |
process { | |
if ($Ordered) { | |
$output = [Ordered]@{} | |
} else { | |
$output = @{} | |
} | |
foreach ($line in $StringData -split '\r?\n') { | |
$line = $line.Trim() | |
if (-not $line -or $line[0] -eq '#') { | |
continue | |
} | |
if ($line -notmatch $splitPattern) { | |
$errorRecord = [System.Management.Automation.ErrorRecord]::new( | |
[InvalidOperationException]::new('Unable to split line "{0}", no delimiter present' -f $line), | |
'InvalidDataLine', | |
'InvalidData', | |
$line | |
) | |
$PSCmdlet.WriteError($errorRecord) | |
continue | |
} | |
$key, $value = $line -split $splitPattern, 2 | |
if ($output.Contains($key)) { | |
$errorRecord = [System.Management.Automation.ErrorRecord]::new( | |
[InvalidOperationException]::new('The key "{0}" already exists in the record' -f $key), | |
'DataItemAlreadyDefined', | |
'InvalidData', | |
$line | |
) | |
$PSCmdlet.WriteError($errorRecord) | |
continue | |
} | |
$output[$key] = [Regex]::Unescape($value) | |
} | |
$output | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment