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.
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 } |
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')} |
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