Search code examples
powershellfor-loopregistry

Nested for loop for creating registry-paths


The idea is, to create a script for cleaning up windows clients in a training center. I want to use for loops to create paths in the registry that i want to delete.

Here's what I have:

$OfficePath = "HKCU:\Software\Microsoft\Office\"
$OfficeVer = "11.0" , "12.0" , "14.0", "15.0"
$OfficeSlice = "word", "excel" , "Outlook" , "onenote" , "Access", "Powerpoint"

for ($ver = 0; $ver -lt $OfficeVer.Count; $ver++)
{ 
for ($slice = 0; $slice -lt $OfficeSlice.Count; $slice++)
{ 
    Remove-Item $OfficePath\$officever[$ver]\$OfficeSlice[$slice] -WhatIf

}
}

What i expect to happen:

For loops create commands like:

Remove-Item "HKCU:\Software\Microsoft\Office\11.0\Word"
Remove-Item "HKCU:\Software\Microsoft\Office\11.0\Excel"
...

But nothing happens at all.

Thanks for help.


Solution

  • Add the Join-Path to your script to deal with the Path-Join:

    $OfficePath = "HKCU:\Software\Microsoft\Office\"
    $OfficeVer = "11.0" , "12.0" , "14.0", "15.0"
    $OfficeSlice = "word", "excel" , "Outlook" , "onenote" , "Access", "Powerpoint"
    
    for ($ver = 0; $ver -lt $OfficeVer.Count; $ver++)
    { 
    for ($slice = 0; $slice -lt $OfficeSlice.Count; $slice++)
    { 
        $Path = (Join-path (Join-Path $OfficePath $officever[$ver]) $OfficeSlice[$slice])
        if (Test-Path $Path)
        {
        Remove-Item $Path -WhatIf
        }
    }
    }