具有多个路径的 Get-ChildItem - 如果目录丢失则出错

Get-ChildItem with multiple paths - Error if directory is missing

我正在使用 Get-ChildItem 收集多个路径中的文件。

例如

Get-ChildItem -Path c:\Test1, c:\Test2 -Filter *.xmd -Recurse -File

如果其中一个目录丢失,我会收到类似这样的错误

Get-ChildItem : Access to the path 'C:\windows\temp" is denied.

第一,我不明白为什么要搜索这个目录,第二,有什么办法可以避免这种情况?

我猜这些路径之一不存在。 Get-ChildItem 有一些违反直觉的行为。它可能是解释输入、遗留功能和一两个错误的混合体。

如果您不使用 -Recurse,您将收到预期的 Cannot find path ... 错误。 如果您在路径中添加反斜杠,它也会正常工作:

Get-ChildItem -Path c:\Test1\, c:\Test2\ -Filter *.xmd -Recurse -File

或使用-LiteralPath-Path接受通配符):

Get-ChildItem -LiteralPath c:\Test1, c:\Test2 -Filter *.xmd -Recurse -File

如果您不希望执行在缺少路径错误时停止,请添加 -ErrorAction Continue-ErrorAction SilentlyContinue