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

1
  • 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. Commented Jan 10, 2023 at 22:37

1 Answer 1

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 
    } 
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.