Home > Blockchain >  Increment a 6 digits number with leading zero and store it in a file
Increment a 6 digits number with leading zero and store it in a file

Time:06-27

I'm trying to make a powershell app that is using an incremental number to create directory in a NAS. The objective is to put "000001" before the name of the directory. I'd like to increment this number by putting it in a file and re-using it. I can only increment without leading 0 so I'm asking for help. This is what I have now.

Getting the content of the txt

Clear the content

Transform it into int

Increment

Add the content.

Transform it into string

        $nb = Get-Content "C:\Users\test\nb.txt"
        Write-Host $nb
        clear-content "C:\Users\test\nb.txt"
        $nb = $nb -as [int]
        $nb = $nb   1
        ADD-content -path "C:\Users\test\nb.txt" -value $nb
        Write-Host $nb
        $nb = $nb -as [string]

CodePudding user response:

Once you have $nb from the file, you can create the string with leading zeroes using the format operator:

'{0:000000}' -f (([int]$nb) )

So, if $nb was 10 when read in, the output would be:

PS >000011

Of course, you can capture it in $nb again if you need to:

[string]$nb = '{0:000000}' -f (([int]$nb) )

Note: $nb is an int, so you will need to cast it to keep the leading zeros, or PowerShell will convert the string 000011 back to 11 (an int) again.

  • Related