powershell format a value that's already a string

6,931

Presumably you're trying to format them this way so that they all show up nicely aligned.

The only problem is that 020 isn't the same as 20. Not according to this anyway.

Windows for Workgroups with TCP/IP-32 and Windows NT utilities can accept Internet Protocol (IP) addresses comprised of decimal, octal, or hexadecimal numbers. This can cause confusion if you unintentionally use a leading zero in a decimal octet. With a leading zero, the number is resolved by these utilities as an octal number, thus specifying the wrong IP address.

The article says that it only applies to WIndows 2000 and NT, but I just tried it on my Windows 7 PC and it's the same story.

To answer your initial question anyway, use the PadLeft method:

$Test = 1
$Test.ToString().PadLeft(3, '0')
001
Share:
6,931

Related videos on Youtube

Eric C. Singer
Author by

Eric C. Singer

Updated on September 18, 2022

Comments

  • Eric C. Singer
    Eric C. Singer over 1 year

    I have some values that I want formatted in a specific way. To be very clear, its an IP address octet and I want it in a "xxx" format. For example if I have a octet value of "20" I want to display it as "020" not "20".

    I'm ultimately going to have an array filled with IP's and I want to properly format all of them.

    Here is one example that I know works, and I've figured out vie a get-member that this is an integer.

    $Test = 1
    
    $Test.ToString("000")
    
    001
    

    This does NOT work. I've figured out via a Get-Member that the value is a string already.

    $Test = "1"
    
    $test.ToString("000")
    
    Cannot find an overload for "tostring" and the argument count: "1".
    At line:1 char:2
    + $test.tostring("000")
    +  ~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodException
        + FullyQualifiedErrorId : MethodCountCouldNotFindBest
    

    Any idea on how I can get the value that's already a string formatted like i can with the value that's an integer? Long term i'm hoping the example $test will actually contain a full IP address.

    For example 10.10.10.10 I'd like to be 010.010.010.010

    Answer For those interested. By utilizing @GregL example I was able to put together a working example for a full IP format with leading zeros which is shown below for reference.

    $Test = "10.10.10.10"
    $test2 = ($test.Split(".") | ForEach-Object {$_.tostring().padleft(3, '0')}) -join "."
    
    • jscott
      jscott about 9 years
      .TosString() isn't a method. Is that a typo?
    • Eric C. Singer
      Eric C. Singer about 9 years
      yes, but the result is the same
  • jscott
    jscott about 9 years
    +1 Beat me to it whilst editing.
  • GregL
    GregL about 9 years
    @jscott: That'll teach you to edit anything! :)
  • Eric C. Singer
    Eric C. Singer about 9 years
    Thank you this is exactly what I needed to put everything together.