Search code examples
powershellstring-formattingip-address

Pad IP addresses with leading 0's - powershell


I'm looking to pad IP addresses with 0's

example
1.2.3.4 -> 001.002.003.004
50.51.52.53 -> 050.051.052.053

Tried this:

[string]$paddedIP = $IPvariable
[string]$paddedIP.PadLeft(3, '0')

Also tried split as well, but I'm new to powershell...


Solution

  • You can use a combination of .Split() and -join.

    ('1.2.3.4'.Split('.') | 
        ForEach-Object {$_.PadLeft(3,'0')}) -join '.'
    

    With this approach, you are working with strings the entire time. Split('.') creates an array element at every . character. .PadLeft(3,'0') ensures 3 characters with leading zeroes if necessary. -join '.' combines the array into a single string with each element separated by a ..


    You can take a similar approach with the format operator -f.

    "{0:d3}.{1:d3}.{2:d3}.{3:d3}" -f ('1.2.3.4'.Split('.') |
        Foreach-Object { [int]$_ } )
    

    The :dN format string enables N (number of digits) padding with leading zeroes.

    This approach creates a string array like in the first solution. Then each element is pipelined and converted to an [int]. Lastly, the formatting is applied to each element.