I have the following script. It will run without a problem when it is not in parallel. But when I add -Parallel
it throws all kinds of errors. The primary error seems to relate to Cannot index into a null array
. I using PS 7.3.3. Any suggestions?
Non-parallel portion of script (start of script)
$fileList=(get-childitem -filter *.tif -recurse | Where-Object {$_.name -match '^[0-9]{3} (B|F) [A-Z]{2} ..K..b [0-9]{2}.*'}).Name
$fileNumbers=($fileList.Substring(0,3) | Sort-Object | Get-Unique)
$fileArr=New-Object 'Object[,]' $fileNumbers.length,5
for ($i=0; $i -lt $fileNumbers.length; $i++) {
$fileArr[$i,0]=$fileNumbers[$i]
$iStr="{0:d3}" -f ($i+1)
$backFullName=@()
$backName=@()
$frontFullName=@()
$backFullName+=(Get-ChildItem -filter "$iStr B *.tif" -recurse | Sort-Object).FullName
$frontFullName+=(Get-ChildItem -filter "$iStr F CC*.tif" -recurse | Sort-Object).FullName
$backName+=(Get-ChildItem -filter "$iStr B*.tif" -recurse | Sort-Object).Name
$frontName+=(Get-ChildItem -filter "$iStr F CC*.tif" -recurse | Sort-Object).Name
if ($backName[0] -eq $null) {
$backLabel=$null
}
else {
$backLabel=("BRP "+$backName[0].Substring(16,2)+" "+$istr)
}
if ($frontName[0] -eq $null) {
$frontLabel=$null
}
else {
$frontLabel=("BRP "+$frontName[0].Substring(16,2)+" "+$istr)
}
$fileArr[$i,1]=$backFullName[0]
$fileArr[$i,2]=$frontFullName[0]
$fileArr[$i,3]=$backLabel
$fileArr[$i,4]=$frontLabel
}
Parallel portion of the script (second half of script)
0..($fileNumbers.length-1) | ForEach-Object -Parallel {
if ($using::fileArr[$_,3] -eq $null -and $using::fileArr[$_,4] -ne $null) {
$label=$using::fileArr[$_,4]
}
elseif ($using::fileArr[$_,3] -ne $null -and $using::fileArr[$_,4] -eq $null) {
$label=$using::fileArr[$_,3]
}
else {
$label=$using::fileArr[$_,3]
}
$locationA=Get-Random
Convert +append $using::fileArr[$_,2] $using::fileArr[$_,1] x:$locationA.jpg
$height=[string](([int](identify -format "%h" x:$locationA.jpg)+400))
$width=(identify -format "%w" x:$locationA.jpg)
$halfWidth=([int]$width*.4)
$dimensions=$width+"x"+$height
$locationB=Get-Random
convert x:$locationA.jpg -gravity north -extent $dimensions x:$locationB.jpg
$str="text $halfWidth,50 '$label'"
convert x:$locationB.jpg -pointsize 300 -gravity southwest -draw "$str" x:$label.jpg
Remove-Item x:$locationA.jpg
Remove-Item x:$locationB.jpg
} -ThrottleLimit 12