Format Leading Zeros in PowerShell

I’ve been working on a question in the forums at ScriptingAnswers.com and the need arose to create a folder name with a 4 digit number. But the number needed to have enough leading zeros so that the number was always 4 digits. For example, Test_0005 or Test_0456. The solution is to use the -f Format operator.

To use this operator on the left side of the statement is a formatting directive and on the right side of -f operator is the value to be formatted. To get the leading zeros I’m going to use a formatting string like this:


"{0:0000}"

This basically says, “take a value and make pad it with 4 0s. Here are some examples:


PS C:\> "{0:0000}" -f 4
0004
PS C:\> "{0:0000}" -f 45
0045
PS C:\> "{0:0000}" -f 456
0456
PS C:\> "{0:0000}" -f 4567
4567

Technically, these are string objects, but that’s ok. Let’s see how we might use this.


PS C:\> 1..10 | foreach {
>> $i="{0:0000}" -f $_
>> $dir="c:\test\Target_$i"
>> $file="file_$i.txt"
>> $target=Join-Path -Path $dir -ChildPath $file
>> Write-Host "Updating $target"
>>
>> }
>>
Updating c:\test\Target_0001\file_0001.txt
Updating c:\test\Target_0002\file_0002.txt
Updating c:\test\Target_0003\file_0003.txt
Updating c:\test\Target_0004\file_0004.txt
Updating c:\test\Target_0005\file_0005.txt
Updating c:\test\Target_0006\file_0006.txt
Updating c:\test\Target_0007\file_0007.txt
Updating c:\test\Target_0008\file_0008.txt
Updating c:\test\Target_0009\file_0009.txt
Updating c:\test\Target_0010\file_0010.txt
PS C:\>

Within the For loop I’m taking the piped in number and formatting to 4 places with leading zeros. This value is then inserted into variables for paths and files, using Join-Path to combine them. This is a much better technique than trying to concatenate.

I hope you find this useful.

Finding Files in the Path – A Pipeline Perk

I’ve been chipping in on a forum post about finding if a given file exists in any folder within the system environmental %PATH% variable using Windows PowerShell. There are several ways you might approach this. But the best way in my opinion is to leverage the PowerShell pipeline. Perhaps you don’t really need the solution but I think it is a valuable learning opportunity. Continue reading

Friday Fun – Snappy Shortcuts

In one of my recent Prof. PowerShell columns, I wrote about using the Wscript.Shell VBScript object in PowerShell to retrieve special folder paths. Another handy trick is the ability to create shortcut links to either file or web resources. Let me show you how to accomplish this in PowerShell and why you might want to. Continue reading