Search code examples
powershelltext-parsing

Convertfrom-string removes leading zeros


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.


Solution

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