Format variable as 4 digits with leading zeroes
You would use -format
operator:
'{0:d4}' -f $variable
https://ss64.com/ps/syntax-f-operator.html
the above will work if your variable is an integer, if not you can cast it to integer:
'{0:d4}' -f [int]$variable
Just to avoid having PetSerAl's useful help go to waste (should the comment be deleted at some point):
Aside from using the format operator (-f
), which I would consider the preferred approach, you can also use formatting methods provided by the respective value.
If the value is a string (as it seems to be in your case), you can pad it with zeroes:
'26'.PadLeft(4, '0')
If the value is numeric you can format it as a string:
(26).ToString('0000')
Foreach versions of padleft and tostring. The 0 in the first one has to be quoted:
'4' | % padleft 4 '0'
0004
4 | % tostring 0000
0004
Working with a range:
1..10 | % tostring 0000
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
With a prefix:
1..10 | % tostring COMP0000
COMP0001
COMP0002
COMP0003
COMP0004
COMP0005
COMP0006
COMP0007
COMP0008
COMP0009
COMP0010