Ronneih
Ronneih

Reputation: 11

Powershell refer to dynamic variable name

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
}

Upvotes: 1

Views: 1824

Answers (1)

Lee_Dailey
Lee_Dailey

Reputation: 7479

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

Upvotes: 1

Related Questions