Home > Back-end >  When i call an array, it gives me the whole array and not just the part i want to call
When i call an array, it gives me the whole array and not just the part i want to call

Time:01-11

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

CodePudding user response:

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 
    } 
}
  • Related