stringpowershellpadzero-padding

How can I pad a series of hyphen-separated numbers each to two digits?


I am fairly new to PowerShell programming, so need help with set of strings I have as described below:

"14-2-1-1"
"14-2-1-1-1"
"14-2-1-1-10"

I want to pad zero to each number in between - if that number is between 1 and 9. So the result should look like:

"14-02-01-01"
"14-02-01-01-01"
"14-02-01-01-10"

I came up with the following code but was wondering if there is a better/faster solution.

$Filenum = "14-2-1-1"
$hicount = ($Filenum.ToCharArray() | Where-Object{$_ -eq '-'} | Measure-Object).Count
$FileNPad = ''
For ($i=0; $i -le $hicount; $i++) {
    $Filesec= "{$i}" -f $Filenum.split('-')
    If ([int]$Filesec -le 9)
    {
        $FileNPad = "$FileNPad-"+"0"+"$Filesec"
    }
    Else
    {
        $FileNPad="$FileNPad-$Filesec"
    }
}
$FileNPad = $FileNPad.Trim("-"," ")

Solution

  • Instead of trying to manually keep track of how many elements and inspect each value, you can simply split on -, padleft, then join back together with -

    "14-2-1-1","14-2-1-1-1","14-2-1-1-10" | ForEach-Object {
        ($_ -split '-').PadLeft(2,'0') -join '-'
    }
    

    Which outputs

    14-02-01-01
    14-02-01-01-01
    14-02-01-01-10