Convertfrom-string removes leading zeros

三世轮回 提交于 2019-12-10 22:19:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!