Convertfrom-string removes leading zeros
Asked Answered
R

2

3

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.

Reactance answered 3/5, 2018 at 20:23 Comment(2)
The cmdlet seems to do some automatic parsing, and 009 becomes a byte. Would $value -split ':' do?Armed
You could use the template variant and assign types in the template (example 5)Require
P
2

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).

Pulpwood answered 4/5, 2018 at 3:11 Comment(0)
F
0

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
Fecundate answered 4/5, 2018 at 9:42 Comment(1)
Good to see a working example with a template, though your specific example field values are confusing: the first field in the input doesn't have digits, and using 1 as the example value for the 2nd one suggests a number (or, if interpreted as a string, in no obvious way matches 009 other than being composed of digits), which is specifically not desired here. The command does work, however - which I find puzzling, and is one of the reasons I stay away from ConvertFrom-String. Note that simply using x as the example values would suffice in this case: {{Val1:x}:{Val2:x}}.Pulpwood

© 2022 - 2024 — McMap. All rights reserved.