Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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