1

I have a reason why I don't want to use an array. But is it possible to use variable folder$i in the Remove-Item command

Set-Variable -Name "folder1" -Value "c:\windows\temp\1\*"
Set-Variable -Name "folder2" -Value "c:\windows\temp\2\*"
Set-Variable -Name "folder3" -Value "c:\windows\temp\3\*"


for ($i=1; $i -le 3; $i++)
{
Write-Host "folder to delete : Remove-Item –path folder$i -recurse"
Write-Host "$(folder$i)"
Remove-Item –path "$(folder$i)" -recurse
}
1
  • As mentioned by @Lee_Dailey's answer. AFAIK, there isn't (shouldn't) be any reason to refer to a dynamic variable. Instead of a array, did you consider a hashtable? Commented Dec 30, 2019 at 12:00

1 Answer 1

1

generally speaking, NOT using an array for this is ... a really good self-foot-gun situation. [grin]

however, if you have found some bizarre reason to NOT use the logical method, the following will work. it uses the Get-Variable cmdlet to do the actual work.

$Var1 = 'Variable_One'
$Var2 = 'Two_Variable'

foreach ($Index in 1..2)
    {
    Get-Variable -Name "Var$Index" -ValueOnly
    }

output ...

Variable_One
Two_Variable
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.