I need to look for variables ending in 01 02 03 etc until the variable doesn't exist, then continue with the script. In this loop iteration 01 is repeated before continue to 02 03 04 05 etc. Why is 01 repeated?
My variables end in a double digits so I convert the integer to a string before looking for the variable. I've managed to work around the issue I'm having by incrementing $i again before entering the loop which is fine, but I'm a little perplexed.
Initial script that iterates 01 twice
$i=1
$CopyFiles_Content_No = ($i).ToString('00')
do {
$CopyFiles_Contents += (Get-Item env:$($CopyFiles_Step)_Contents$($CopyFiles_Content_No)).Value
$CopyFiles_Content_No = ($i++).ToString('00')
} while (Test-Path env:$($CopyFiles_Step)_Contents$($CopyFiles_Content_No) -ErrorAction Ignore)
To replicate this easily just type the following into Powershell
$i=1 #Set Int
$CopyFiles_Content_No = ($i).ToString('00') #Convert to double digit string
$CopyFiles_Content_No #See output which is 01
$CopyFiles_Content_No = ($i++).ToString('00') #Increment $i and assign to variable
$CopyFiles_Content_No #See output which is still 01
$CopyFiles_Content_No = ($i++).ToString('00') #Increment $i and assign to variable
$CopyFiles_Content_No #See output which is 02
$CopyFiles_Content_No = ($i++).ToString('00') #Increment $i and assign to variable
$CopyFiles_Content_No #See output which is 03
Work around is to increment $1 before entering the loop
$i=1
$CopyFiles_Content_No = ($i++).ToString('00')
do {
$CopyFiles_Contents += (Get-Item env:$($CopyFiles_Step)_Contents$($CopyFiles_Content_No)).Value
$CopyFiles_Content_No = ($i++).ToString('00')
} while (Test-Path env:$($CopyFiles_Step)_Contents$($CopyFiles_Content_No) -ErrorAction Ignore)