Put zero in front of a string

by leitsu at 2013-04-17 23:27:07

Hi
If I have a string. The string can be any number but needs to be four digits. I need to put zero in front of the string. How do I do that
For example,
38 -> 0038
1234 -> 1234
1 -> 0001
100 -> 0100
by Ernie at 2013-04-17 23:56:36
One way would be to yse the PadLeft method of the string class as below

[string]$String = "0038","55","430","09"

$String | foreach {$.PadLeft(4,‘0’)}

Hope that helps
Ernie
by Ernie at 2013-04-18 00:00:10
A little more explanation

Basically the above code will insert a Zero infront of each string if the said sting is less than four characters long in the first instance

Ernie
by mjolinor at 2013-04-18 03:52:45
Another option is to use a format string.

38,1234,1,100 |
foreach {'{0:0###}' -f $
}
0038
1234
0001
0100