问题
Im having a problem with the Convertfrom-String cmdlet
$value = 'something:009'
$value | ConvertFrom-String -Delimiter ':'
Output:
P1 P2
-- --
something 9
The output i want is
P1 P2
-- --
something 009
Anyone got any ideas?
Thanks in advance.
回答1:
I suggest avoiding ConvertFrom-String altogether - it performs type conversions that you cannot control when you use -Delimiter
, as you've experienced, and its example-driven template-based parsing is awkward.
On a side note: ConvertFrom-String
is not available in the cross-platform PowerShell Core edition.
In your simple case, use ConvertFrom-Csv
instead:
$value = 'something:009'
$value | ConvertFrom-Csv -Delimiter ':' -Header P1, P2
ConvertFrom-Csv
reads all values as strings, as-is (with string input; enclosing double quotes around field values are removed).
回答2:
mklement0 propose the best solution. You can do it too :
Solution 1 : with a simple split (not you can split with regex too)
$value = 'something:009'
$values=$value -split ':'
[pscustomobject]@{
Val1=$values[0]
Val2=$values[1]
}
Solution 2 : with ConvertFrom-String and a Template
$template=@"
{{Val1:Abc123}:{Val2:1}}
"@
$value = 'something:009'
$value | ConvertFrom-String -TemplateContent $template
来源:https://stackoverflow.com/questions/50163311/convertfrom-string-removes-leading-zeros