Here is a piece of code I tested for the conversion of the numbers 0 thru 99 into 20 strings of exactly 2 digits. The first is 04, the next 09, then 14,19,24,29, etc. all the way to 94, 99.
The code: "{0:D2}" -f $d formats each number to exactly 2 digits.
The $i used in the “for” loop is interpreted by PowerShell – it automatically assigns it to a float. So when dividing by 5, we get fractions. I needed it to be whole numbers, hence the [math]::floor($i/5).
cls
for ($i = 0; $i -lt 100; $i++)
{
$n = [math]::floor($i/5)
$d = $n * 5 + 4
"{0:D2}" -f $d
}
I erroneously assumed that the result $d will be formattable ("{0:D2}" -f $i renders the desired result), alas this results in the following error:
Error formatting a string: Format specifier was invalid..
At E:\HA\testformat.ps1:6 char:2
+ "{0:D2}" -f $d
+ ~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: ({0:D2}:String) [], RuntimeException
+ FullyQualifiedErrorId : FormatError
I tried all sorts of things, but the error was persistent, then I tried coercing – the PowerShell term for casting. I used [float] and [decimal] to no avail, but my 3rd (and obviously last*) attempt was [int] and it worked.
cls
for ($i = 0; $i -lt 100; $i++)
{
$n = [math]::floor($i/5)
[int]$d = $n * 5 + 4
"{0:D2}" -f $d
}
Generated the desired results.
* Why is it that we always find what we look for in the VERY LAST place we looked?
That’s all Folks