[PowerShell] Convert 1 digit number to 2 digit number

Soldato
Joined
25 Mar 2004
Posts
15,766
Location
Fareham
Hi all,

Is there a way in PowerShell to convert a one digit number to a two digit number?

For example:

Code:
$count = 1..10 ; foreach ($number in $count) {$number}

Loops through numbers 1 to 10 and returns them as values $number.

when run you get this:

1
2
3
4
5
6
7
8
9
10

I want this returned instead:

01
02
03
04
05
06
07
08
09
10

So if number is less than 9 it adds a 0 on the front.

I was thinking something like:

Code:
$count = 1..10 ; foreach ($number in $count)
	{
		if ($number -le 9)
		{
		$number = "0" + $number
		}
	$number
	}

If you run this you do get:

01
02
03
04
05
06
07
08
09
10

But it doesn't seem very elegant, is there a better way?

Thanks!
 
Soldato
Joined
19 Dec 2009
Posts
2,669
Location
Lancashire
Legend thanks! :)

P.S Knew about the formatting for decimal places didn't know you could add digits with it though

Yeah, it's one of those things that seems to be less well-known, here at least. Just got to be a bit careful if you want to add leading zeroes on a floating-point number. :p
 
Soldato
OP
Joined
25 Mar 2004
Posts
15,766
Location
Fareham
This is what I was trying to achieve btw, seems to work good now :)

Code:
$CurrentDate = Get-Date
$Time = ""
[string]$Time = "{0:D2}" -f ($CurrentDate.hour) + ":" + "{0:D2}" -f ($CurrentDate.minute) + ":" + "{0:D2}" -f ($CurrentDate.second)

Just wanted the current time in hours:mins:secs to be consistently 2 digits across em all!
 
Back
Top Bottom