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 anint
, so you will need to cast it to keep the leading zeros, or PowerShell will convert the string000011
back to11
(anint
) again.