我正在使用 PowerShell 和 -Parallel 选项来加速一个使用 ImageMagick 检查文件格式的脚本。该脚本无需并行处理也能运行,但处理大量文件时速度太慢。当我添加 -Parallel 选项时,总是出现错误。代码如下——有人能帮我找出问题所在吗?
错误:
无法使用指定的命名参数解析参数集。缺少一个或多个参数、不允许同时使用参数,或者为所选参数集提供的参数数量不足。
代码:
$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 += $_
}
}
更新:
# 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."
}