PowerShell - Get-ChildItem 不排除目录

PowerShell - Get-ChildItem does not exclude directory

递归搜索特定目录时,Get-ChildItem将从根目录开始搜索。我不想搜索 C:\Windows 目录。我想将搜索限制在 C:\Docs 目录。
这就是我 运行:

PS> Get-ChildItem -path “C:\docs” -Filter "*crypt*" -recurse -ErrorAction Stop
Get-ChildItem : Access to the path 'C:\Windows\CSC' is denied.
At line:1 char:1
+ Get-ChildItem -path “C:\docs” -Filter "*crypt*" -recurse -ErrorAction ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\Windows\CSC:String) [Get-ChildItem], UnauthorizedAccessException
    + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand

PS> Get-ChildItem -path “C:\docs” -Filter "*crypt*" -exclude "C:\windows" -recurse -ErrorAction Stop
Get-ChildItem : Access to the path 'C:\Windows\CSC' is denied.
At line:1 char:1
+ Get-ChildItem -path “C:\docs” -Filter "*crypt*" -exclude "C:\windows" ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : PermissionDenied: (C:\Windows\CSC:String) [Get-ChildItem], UnauthorizedAccessException
    + FullyQualifiedErrorId : DirUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand  

编辑:TL;DR:用户错误。我没有 C:\Docs 目录。

我正在编辑这个脚本,它在多个服务器上 运行。我正在我的笔记本电脑上测试它。我仍然不明白为什么它会在找不到起始路径后查看文件系统的其余部分。

看起来(我搜索不够)这可能是 Get-ChildItem 中的一个错误;如果您将不存在的路径传递给 -path 参数,它会从该驱动器的根目录搜索(至少对于本地驱动器)。

在调用Get-ChildItem之前,测试路径是否存在,可以避免这种情况。

$mypath = "c:\docs";
if (test-path -path $mypath) {
    Get-childitem –path $mypath –filter “*crypt*" -recurse -ErrorAction stop;
} else {
    Write-Warning "$mypath not found";
}