powershell loop through arrary in arrary
Olivia Zamora
I'm try to write a powershell script to create a folder and then create files inside that folder.
$arr = @( ("First Folder",@("1", "2")), ("Sceond Folderr", @("1","2")) )
for ($i=0; $i -lt $arr.length; $i++)
{ #New-Item -Path $arr[$i] -ItemType directory for ($a=0; $a -lt $arr[$i].length; $a++) { $file=$arr[$a] #New-Item -Path "$file.txt" -ItemType File $file }
}This is the result I get.
First Folder
1
2
First Folder
1
2
Second Folder
1
2
Second Folder
1
2 2 Answers
The $arr variable is defined as a jagged array:
Jagged arrays vs. Multidimensional arrays:
Both are useful for holding lists of lists or arrays of arrays.
- Jagged is faster and use less memory than multidimensional, because it contains only the number of elements it needs.
- A non jagged array is more like a matrix where every array must be the same size.
The following code snippet shows proper way of handling the particular jagged array $arr:
$arr = @( ("First Folder",@("1", "2")), ("Sceond Folderr", @("11","12")) )
for ($i=0; $i -lt $arr.length; $i++)
{ $dire = $arr[$i][0] #New-Item -Path $dire -ItemType directory for ($a=0; $a -lt $arr[$i].length; $a++) { $file=$arr[$i][1][$a] #New-Item -Path "$dire`\$file`.txt" -ItemType File "$dire`\$file`.txt" }
}Output:
PS D:\PShell> D:\PShell\SU\1285156.ps1
First Folder\1.txt
First Folder\2.txt
Sceond Folderr\11.txt
Sceond Folderr\12.txt
PS D:\PShell> 1 While StackOverflow would be a better place to post this, if you're working with PowerShell there is no real need to use classic for loops.
$arr = @( ("First Folder",@("1", "2")), ("Second Folder", @("1","2")) )
$arr | %{ $folder = $_ Write-Output $folder[0] $folder[1] | %{ Write-Output "SubItem:", $_ }
}The % is a shortcut ForEach-Object. As for your solution use more descriptive variables names to make it easier to understand (for yourself).
$arr = @( ("First Folder",@("1", "2")), ("Sceond Folderr", @("1","2")) )
# ForEach item from 0 to 1
for ($i=0; $i -lt $arr.length; $i++)
{ # ForEach item from 0 to $arr[$i].length # 0, 0 - 1, 0, 0 -1 for ($folderKey=0; $folderKey -lt $arr[$i].length; $folderKey++) { Write-Output "Value for `$i is $i and value for `$folderKey is $folderKey" # Always prints just what's on the index of $i $file=$arr[$i] $file # The fix would be $arr[$i][$folderKey] }
} 3