Skip to content

Instantly share code, notes, and snippets.

@indented-automation
Last active October 8, 2021 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indented-automation/4034593752a05c6c098e1d5d7dd14073 to your computer and use it in GitHub Desktop.
Save indented-automation/4034593752a05c6c098e1d5d7dd14073 to your computer and use it in GitHub Desktop.
A quick replacement for ConvertFrom-StringData which supports ordered dictionary output
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