Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

Powershell adding leading zeros to string or int

I was working on a script project where I wanted to create and defined names for multiple virtual machine in the series, with maintaining length of the string of names with numbers adding leading zeros, Below -f format operator one-liner command helps me to create the list.

1
2
3
1..10 | ForEach-Object {"{0:d4}" -f ($_ * 11)}

1..10 | ForEach-Object {"{0,10}" -f ($_ * 11)}

This works very well with numbers.

Microsoft Powershell padleft foreach-object -f operator format operator scripting adding leading 0 zero padright string and integer int.png

Using the same technique I have created some interesting math function as below.

1
2
3
4
5
6
7
$numbers = 1..9
foreach ($number in $numbers) {
    $spaces = $numbers[-$number]
    [int]$range = 1..$number -join ''
    $result = ($range * 8) + $number
    "{0, $spaces}{1} X 8 + {2} = {3}" -f '', $range, $number, $result
}

Microsoft PowerShell numbers -f operator foreach foreach-object -join operator padleft add leading 0 zeroes servernames filenames.png

There is alternative option, if you are looking to add 0 or spaces in front of string, there is method called padleft() on the string and it is as below.

1
2
3
'a.doc', 'abc.doc', 'newsbbc.doc' | ForEach-Object {$_.padleft(15)}

'a.doc', 'abc.doc', 'newsbbc.doc' | ForEach-Object {$_.padleft(15,'0')}

Microsoft PowerShell numbers -f operator foreach foreach-object -join operator padleft add leading 0 zeroes servernames filenames padleft and padright string integer int.png

Useful articles
Installing, importing and using any module in powershell
Microsoft PowerShell: Check Windows license activation status
Find next available free drive letter using PowerShell
Copy Files with PowerShell Remoting WINRM Protocol
Powershell Find application window state minimized or maximized

Go Back

Comment

Blog Search

Page Views

12278893

Follow me on Blogarama