Reputation: 831
I need to be able to print off a range of numbers only as double digits. For example, 01,02,03,04...10,11
.
This is the script I am trying it in:
# Define a range's upper bound dynamically (IRL via user input)
$upperBound = 18
# Create an array of numbers (indices).
1..$upperBound
I tried using "{0:D2}" as the above site stated but I got a error "Cannot convert value":
1.."{0:D2}" -f $upperBound
I also tried this;
"{0:D2}" -f $upperBound
However, this only display the one number that was entered, not the entire range. For example, if I enter 2, I will get 02. I would like it to display 01,02.
In addition to this, I would like this range to be displayed next to a server name. I have a list of servers and this range would have to be attached to the server name. Example:
server01
server02
Upvotes: 1
Views: 2173
Reputation: 2268
$upperbound = 18
$totalArray = 1..$upperbound | foreach {$_.tostring('00')}
foreach ($server in (cat serverlist.txt)) {
$totalarray | foreach {"$server$_"}
}
replace 00 with how many places you want 0's to take
0 = 1,2,3 etc..
00 = 01, 02, 03 etc...
000 = 001, 002, 003 etc..
if you want to display server digits in a single line with commas you could just do
$totalArray -join ','
Upvotes: 0
Reputation: 440679
The range operator (..
) only operates on numbers as endpoints; in order to format the resulting array of numbers you must apply post-processing on the elements of the array created by ..
:
Note: The sample output below assumes that $upperBound
has a value of 3
.
Using PSv4+ syntax:
PS> (1..$upperBound).ForEach({ '{0:D2}' -f $_ })
01
02
03
In PSv3-, use:
foreach ($ndx in 1..$upperBound) { '{0:D2}' -f $ndx } # same output as above.
To make the formatted "number strings" part of a server name:
PS> (1..$upperBound).ForEach({ 'server{0:D2}' -f $_ })
server01
server02
server03
In order to create a list of names as a single string with separators, use the -join
operator on the resulting array:
PS> (1..$upperBound).ForEach({ 'server{0:D2}' -f $_ }) -join ','
server01,server02,server03
In PSv3-:
$(foreach ($ndx in 1..$upperBound) { 'server{0:D2}' -f $ndx }) -join ','
Upvotes: 1