I'm using PowerShell with -Parallel to speed up a script that checks file formats using ImageMagick. The script works without parallel processing, but it's too slow with a large number of files. When I add -Parallel, I keep getting an error. Here's the code—can someone help me figure out what's going wrong?
Error:
Parameter set cannot be resolved using the specified named parameters. One or more parameters are either missing, not allowed together, or an insufficient number of parameters have been provided for the selected parameter set.
Code:
$files | ForEach-Object -Parallel {
param ($file, $magickPath, $errorLogFile)
try {
# Run ImageMagick to identify the format
$output = & $magickPath identify -ping -quiet -format "%m" $file.FullName
# Check if the image is NOT JPEG or PNG
if ($output -ne "JPEG" -and $output -ne "PNG") {
$fileName = $file.Name
"$fileName - $output"
}
}
catch {
# Log errors
$errorMsg = "Error processing file: $($file.FullName). Error: $($_.Exception.Message)"
$errorMsg | Out-File -FilePath $errorLogFile -Append
}
} -ThrottleLimit 8 -ArgumentList $magickPath, $errorLogFile | ForEach-Object {
if ($_ -ne $null) {
$nonJpegPngFiles += $_
}
}
Update:
# Folder where the images are located
$folderPath = "C:\Users\johndoe\Documents\saved images"
# File where unsupported image names will be saved
$outputFile = "C:\Users\johndoe\Documents\Unsupported list\unsupported_images_list.txt"
# Path to ImageMagick executable
$magickPath = "C:\Program Files\ImageMagick-7.1.1-016\magick.exe"
# Get all files in the folder
$files = Get-ChildItem -Path $folderPath -File
# Process files in parallel
$result = $files | ForEach-Object -Parallel {
# Run ImageMagick to identify the format, redirecting stderr to stdout
$output = & $using:magickPath identify -ping -quiet -format '%m' $_.FullName 2>&1
# Return the file path and output for filtering later
[pscustomobject]@{
Path = $_.FullName
Output = $output
}
} -ThrottleLimit 8
# Filter files that are not JPEG or PNG
$unsupportedFiles = $result | Where-Object { $_.Output -notin 'JPEG', 'PNG' }
# If unsupported files exist, write them to the output file
if ($unsupportedFiles.Count -gt 0) {
$unsupportedFiles | Select-Object -ExpandProperty Path | Out-File -FilePath $outputFile
Write-Host "List of unsupported files has been saved to $outputFile."
} else {
Write-Host "No unsupported files found."
}
-ArgumentListcannot be used with-Parallel, you'll need to either hardcode the paths or resolve them from the callsite with$using:magickPathfor example