我对下面的代码有疑问,并且无法弄清楚为什么我丢失了一些东西。有人可以帮我吗?我还包含了该错误,我正在使用 PowerShell v7。
谢谢
错误:
Line |
109 | $results = $files | ForEach-Object -Parallel {
| ~~~~~~~~~~~~~~~~~~~~~~~~~~
| Parameter set cannot be resolved using the specified named parameters. One or more parameters issued cannot be
| used together or an insufficient number of parameters were provided.
代码:
$allResults = @()
foreach ($searchPath in $searchPaths) {
if (!(Test-Path -Path $searchPath)) {
Write-Output "Path does not exist: $searchPath"
continue
}
Write-Output "Searching in path: $searchPath"
# Get all files in the search path with specified types
$files = Get-ChildItem -Path $searchPath -Recurse -Force -ErrorAction SilentlyContinue | Where-Object {
$fileTypes -contains $_.Extension.ToLower()
}
# Ensure that we have files to process
if ($files.Count -eq 0) {
Write-Output "No files found in path: $searchPath"
continue
}
# Process files in parallel
$results = $files | ForEach-Object -Parallel {
param (
[string]$FilePath,
[hashtable]$Patterns
)
try {
# Call the search function and return results
return Search-PIIInFile -filePath $FilePath -patterns $Patterns
} catch {
Write-Output "Error processing file ${FilePath}: $_"
}
} -ArgumentList $_.FullName, $patterns -ThrottleLimit 10
# Aggregate results from parallel processing
$allResults += $results
}
-ArgumentList
仅在 PropertyAndMethodSet
参数集中可用:
(Get-Command ForEach-Object).Parameters['ArgumentList'].ParameterSets
# Key Value
# --- -----
# PropertyAndMethodSet System.Management.Automation.ParameterSetMetadata
并且
-Parallel
仅在 ParallelParameterSet
参数集中可用:
(Get-Command ForEach-Object).Parameters['Parallel'].ParameterSets
# Key Value
# --- -----
# ParallelParameterSet System.Management.Automation.ParameterSetMetadata
这就是您收到此错误的原因,
-Parallel
和-ArgumentList
由于不在同一参数集中而无法一起使用。
$using:
范围修饰符获取局部变量并删除 -ArgumentList
来修复代码:
$results = $files | ForEach-Object -Parallel {
$FilePath = $using:_.FullName
$Patterns = $using:patterns # <= unclear where is `$Patterns` defined outside this context
try {
# Call the search function and return results
return Search-PIIInFile -filePath $FilePath -patterns $Patterns
}
catch {
Write-Output "Error processing file ${FilePath}: $_"
}
}