The Problem:

Imagine you’re generating a series of files named sequentially: file01.txt, file02.txt, … file10.txt, and so on. If you simply increment a number, you’ll end up with file names like file1.txt, file2.txt, which might not align properly or sort correctly in some systems.

The Solution:

for ($i = 1; $i -le 10; $i++) {
    $formattedNumber = "{0:D2}" -f $i
    Write-Output $formattedNumber
}

In this script, the magic happens in the line $formattedNumber = "{0:D2}" -f $i. Let’s break it down:

  • "{0:D2}": This is a format string.
    • {0} refers to the first (and in this case, only) variable provided after the -f operator.
    • D2 specifies that the number should be formatted as a decimal with two digits.
  • -f: This is the format operator in PowerShell. It applies the format string on the left to the variables on the right.

When you run the script, it will output:

01
02
03
...
10


0 commentaire

Laisser un commentaire

Emplacement de l’avatar

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.