1

I have a for loop that needs to loop the number of times there are folders in a folder.

what i have is:

$Thickness = Get-ChildItem $PSScriptRoot |
             Where-Object {$_.PSIsContainer} |         #Gets the names of folders in a folder
             ForEach-Object {$_.Name}

for($Counter=0;$Counter -lt $Thickness.Count;$Counter++){      
    if(!(Test-Path -Path "$PSScriptRoot\$Thickness[$Counter]\Previous Years")){    #Test if there is a folder called "Previous years" in each folder
           new-Item -Path "$PSScriptRoot\$Thickness[$Counter]\Previous Years" -ItemType Directory #If folder "Previous Years" Does not exist, create one  
    } 
}

What happened when i run this is that it creates a folder called all the values in the array with the Value of Counter in Brackets

What i get now

mklement0
  • 382,024
  • 64
  • 607
  • 775
FrancoisB
  • 27
  • 4
  • In short: Only variables _by themselves_ can be embedded as-is in expandable strings (`"..."`), e.g. `"foo/$var"` or `"foo/$env:USERNAME"`. To embed _expressions_ or even commands, you must enclose them in `$(...)`. Notably, this includes property and indexed access (e.g., `"foo/$($var.property)"`, `"foo/$($var[0])"`). See the linked duplicate for details. – mklement0 Jan 10 '23 at 22:37

1 Answers1

1

Only simple variable expressions (like $Thickness) is expanded in double-quoted strings - to qualify the boundaries of the expression you want evaluated, use the sub-expression operator $(...):

"$PSScriptRoot\$($Thickness[$Counter])\Previous Years"

Another option is to skip the manual counter altogether and use a foreach loop or the ForEach-Object cmdlet over the array:

foreach($width in $Thickness){
    $path = "$PSScriptRoot\$width\Previous Years"
    if(!(Test-Path -Path $path)){
        New-Item -Path $path -ItemType Directory 
    } 
}
# or 
$Thickness |ForEach-Object {
    $path = "$PSScriptRoot\$_\Previous Years"
    if(!(Test-Path -Path $path)){
        New-Item -Path $path -ItemType Directory 
    } 
}
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206