第一次在这里提问。请善待:)
我试图以并行方式递归地获取所有目录,希望减少遍历驱动器所需的时间。下面是我尝试过的代码。本质上我想要做的是输入一个文件夹,并对其子文件夹及其子文件夹等并行执行相同的操作,但该函数在并行块内无法识别
function New-RecursiveDirectoryList {
[CmdletBinding()]
param (
# Specifies a path to one or more locations.
[Parameter(Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Path to one or more locations.')]
[Alias('PSPath')]
[ValidateNotNullOrEmpty()]
[string[]]
$Path
)
process {
foreach ($aPath in $Path) {
Get-Item $aPath
Get-ChildItem -Path $aPath -Directory |
# Recursively call itself in Parallel block not working
# Getting error "The term 'New-RecursiveDirectoryList' is not recognized as a name of a cmdlet"
# Without -Parallel switch this works as expected
ForEach-Object -Parallel {
$_ | New-RecursiveDirectoryList
}
}
}
}
Error:
New-RecursiveDirectoryList:
Line |
2 | $_ | New-RecursiveDirectoryList
| ~~~~~~~~~~~~~~~~~~~~~~~~~~
| The term 'New-RecursiveDirectoryList' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
我还尝试使用 mklement0 提供的解决方案here但没有运气。以下是我对此的尝试:
function CustomFunction {
[CmdletBinding()]
param (
# Specifies a path to one or more locations.
[Parameter(Mandatory = $true,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
HelpMessage = 'Path to one or more locations.')]
[Alias('PSPath')]
[ValidateNotNullOrEmpty()]
[string[]]
$Path
)
begin {
# Get the function's definition *as a string*
$funcDef = $function:CustomFunction.ToString()
}
process {
foreach ($aPath in $Path) {
Get-Item $aPath
Get-ChildItem -Path $aPath -Directory |
# Recursively call itself in Parallel block not working
# Getting error "The term 'New-RecursiveDirectoryList' is not recognized as a name of a cmdlet"
# Without -Parallel switch this works as expected
ForEach-Object -Parallel {
$function:CustomFunction = $using:funcDef
$_ | CustomFuction
}
}
}
}
Error
CustomFuction:
Line |
3 | $_ | CustomFuction
| ~~~~~~~~~~~~~
| The term 'CustomFuction' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
有谁知道如何实现这一点或以不同的方式实现这一点?