In PowerShell 5 the ConvertFrom-StringData
cmdlet does not have a Delimiter
parameter and always uses the equals sign (=
) as separator between the name and value of the input.
Also, ConvertFrom-StringData
always returns a Hashtable, which is unordered by default.
$txt = Get-Content -Path 'TheFile.txt' -Raw
[PsCustomObject]@{'colors-20220906' = ($txt -replace ':', '=' | ConvertFrom-StringData )} | ConvertTo-Json
results in
{
"colors-20220906": {
"blue": "2",
"yellow": "3",
"orange": "1"
}
}
If the order of subitems is important to you, you need to split the key:value lines yourself:
$txt = Get-Content -Path 'TheFile.txt'
# create an ordered Hash to retain the order in which the items appear
$hash = [ordered]@{}
foreach ($line in $txt) {
$name,$value = ($line -split ':', 2).Trim()
$hash[$name] = $value
}
[PsCustomObject]@{'colors-20220906' = $hash} | ConvertTo-Json
results in
{
"colors-20220906": {
"orange": "1",
"blue": "2",
"yellow": "3"
}
}
P.S. PowerShell creates valid JSON, but the format is quite ugly. If you want to prettify that, you can use the function I posted earlier Format-Json