如何使用Powershell搜索文件夹

mad*_*ads 18 powershell

我想搜索特定目录和子目录中的文件夹.

我试过谷歌搜索,但没有找到任何有用的例子.

Ada*_*ski 42

Get-ChildItem C:\test -recurse | Where-Object {$_.PSIsContainer -eq $true -and $_.Name -match "keyword"}
Run Code Online (Sandbox Code Playgroud)

我相信没有用于搜索文件的专用cmdlet.

编辑回应@Notorious评论:由于PowerShell的3.0,这是很容易的,因为交换机-Directory-File加入Get-ChildItem.所以,如果你想要它简短,你就得到:

ls c:\test *key* -Recurse -Directory
Run Code Online (Sandbox Code Playgroud)

使用命令别名和开关的tab-completion,它很容易.我第一次错过了.

  • 对于那些不太熟悉的Powershell,表达式'$ _. PSIsContainer -eq $ true'是对当前对象作为文件夹的测试. (6认同)
  • -Directory仅在较新版本的Powershell中起作用。同样对于任何新手来说,`Get-ChildItem == ls == gci` (3认同)

atu*_*urc 6

这是我的版本,仅略有不同:

gci -Recurse -Filter "your_folder_name" -Directory -ErrorAction SilentlyContinue -Path "C:\"
Run Code Online (Sandbox Code Playgroud)

更多信息:

-Filter "your_folder_name"
Run Code Online (Sandbox Code Playgroud)

来自文档:过滤器比其他参数更有效。提供程序在 cmdlet 获取对象时应用筛选器,而不是让 PowerShell 在检索对象后筛选对象。过滤器字符串被传递到 .NET API 以枚举文件。该 API 仅支持 * 和 ? 通配符。

-Directory 
Run Code Online (Sandbox Code Playgroud)

只检查目录,也可以是-File

-ErrorAction SilentlyContinue 
Run Code Online (Sandbox Code Playgroud)

消除任何警告

-Path "C:\"
Run Code Online (Sandbox Code Playgroud)

指定开始搜索的路径

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-7