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 "."
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.
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:I use these great Subnet Math functions written by Chris Dent. Store your list of addresses in the pure decimal (not dotted decimal) or pure binary values. Sort the list, then retrieve the list, and finally display the list utilizing the ConvertTo-DottedDecimalIP function. Lots of other great subnet functions in his blog.