I could use some help with nested loops in PowerShell. I have a document which has item names. I have a folder full of images. I'm looping through the item names and testing if there are any images for that item. An item will only be listed in the document once, but it may have multiple images. For example, ItemXYZ in the doc could have ItemXYZ, ItemXYZ_1, and ItemXYZ_2 in the images folder. This code works for what I'm attempting to do:
for ($i=2; $i -le $rowCount; $i++) {
Write-Host -NoNewline ("Checking line $i of $rowCount`n")
$item = $worksheet.Cells.Item($i,1).Text #Item(row,column)
foreach ($image in $images) {
if ("ABC-$item" -eq $image.BaseName) {
$worksheet.Cells.Item($i,21).Value = $hyperlinkchunk1 + $image.FullName + $hyperlinkchunk2 + $image.Name + $hyperlinkchunk3
Write-Host ("** MATCH **")
}
for ($x=1; $x -le 12; $x++) {
if ('ABC-'+$item+'_'+$x -eq $image.BaseName) {
$z = $x+21
$worksheet.Cells.Item($i,$z).Value = $hyperlinkchunk1 + $image.FullName + $hyperlinkchunk2 + $image.Name + $hyperlinkchunk3
Write-Host ("** MATCH **")
}
}
}
}
The first image for an item will always be just the base name so there is no need to check for the 12 underscore images if the first doesn't exist. Because of this, I want to put the nested for statement within the first if statement (updated code block below). This leads me to the issue. When I make this adjustment I do not get all the matches found by using the first block of code. Any ideas why?
for ($i=2; $i -le $rowCount; $i++) {
Write-Host -NoNewline ("Checking line $i of $rowCount`n")
$item = $worksheet.Cells.Item($i,1).Text #Item(row,column)
foreach ($image in $images) {
if ("ABC-$item" -eq $image.BaseName) {
$worksheet.Cells.Item($i,21).Value = $hyperlinkchunk1 + $image.FullName + $hyperlinkchunk2 + $image.Name + $hyperlinkchunk3
Write-Host ("** MATCH **")
for ($x=1; $x -le 12; $x++) {
if ('ABC-'+$item+'_'+$x -eq $image.BaseName) {
$z = $x+21
$worksheet.Cells.Item($i,$z).Value = $hyperlinkchunk1 + $image.FullName + $hyperlinkchunk2 + $image.Name + $hyperlinkchunk3
Write-Host ("** MATCH **")
}
}
}
}
}
Aucun commentaire:
Enregistrer un commentaire