我正在所有文件夹中搜索文件。
Copyforbuild.bat
在很多地方都有,我想递归搜索。
$File = "V:\Myfolder\**\*.CopyForbuild.bat"
如何在 PowerShell 中执行此操作?
将 Get-ChildItem cmdlet 与 -Recurse
开关一起使用:
Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse -ErrorAction SilentlyContinue -Force
我用它来查找文件,然后让 PowerShell 显示结果的整个路径:
dir -Path C:\FolderName -Filter FileName.fileExtension -Recurse | %{$_.FullName}
您始终可以在 FolderName
和/或 FileName.fileExtension
中使用通配符 *
。例如:
dir -Path C:\Folder* -Filter File*.file* -Recurse | %{$_.FullName}
上面的示例将搜索 C:\
驱动器中以单词 Folder
开头的任何文件夹。因此,如果您有一个名为 FolderFoo
和 FolderBar
的文件夹,PowerShell 将显示这两个文件夹的结果。
文件名和文件扩展名也是如此。如果要搜索具有特定扩展名的文件,但不知道文件名,可以使用:
dir -Path C:\FolderName -Filter *.fileExtension -Recurse | %{$_.FullName}
或相反亦然:
dir -Path C:\FolderName -Filter FileName.* -Recurse | %{$_.FullName}
在搜索可能会出现基于安全性错误的文件夹时(例如 C:\Users
),请使用以下命令:
Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse -ErrorAction SilentlyContinue -Force
Get-ChildItem V:\MyFolder -name -recurse *.CopyForbuild.bat
也会起作用
Get-ChildItem . -name -recurse *.bat
为我工作
以下是我苦苦挣扎后终于想出的方法:
Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*
要使输出更清晰(仅路径),请使用:
(Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*).fullname
要仅获得第一个结果,请使用:
(Get-ChildItem -Recurse -Path path/with/wildc*rds/ -Include file.*).fullname | Select -First 1
现在是重要的东西:
要仅搜索文件/目录,请不使用 -File
或 -Directory
(请参阅下面的原因)。而是将其用于文件:
Get-ChildItem -Recurse -Path ./path*/ -Include name* | where {$_.PSIsContainer -eq $false}
并删除目录的 -eq $false
。请勿不要留下像 bin/*
这样的尾随通配符。
为什么不使用内置开关?它们很糟糕,并且会随机删除功能。例如,要将 -Include
与文件一起使用,您必须以通配符结束路径。但是,这会禁用 -Recurse
开关而不告诉您:
Get-ChildItem -File -Recurse -Path ./bin/* -Include *.lib
您可能认为这会为您提供所有子目录中的所有 *.lib
,但它只会搜索顶级 bin
。
为了搜索目录,您可以使用 -Directory
,但您必须删除尾随通配符。无论出于何种原因,这都不会停用 -Recurse
。正是出于这些原因,我建议不要使用内置标志。
您可以大大缩短此命令:
Get-ChildItem -Recurse -Path ./path*/ -Include name* | where {$_.PSIsContainer -eq $false}
变成
gci './path*/' -s -Include 'name*' | where {$_.PSIsContainer -eq $false}
Get-ChildItem 别名为 gci
-Path 默认为位置 0,因此您可以只创建第一个参数路径
-Recurse 别名为 -s
-Include 没有简写
对名称/路径中的空格使用单引号,以便您可以用双引号将整个命令括起来并在命令提示符中使用。反过来(用单引号括起来)会导致错误
尝试这个:
Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse | Where-Object { $_.Attributes -ne "Directory"}
| Where-Object { !$_PSIsContainer }
排除文件夹
使用通配符过滤:
Get-ChildItem -Filter CopyForBuild* -Include *.bat,*.cmd -Exclude *.old.cmd,*.old.bat -Recurse
使用正则表达式过滤:
Get-ChildItem -Path "V:\Myfolder" -Recurse
| Where-Object { $_.Name -match '\ACopyForBuild\.[(bat)|(cmd)]\Z' }
'\ACopyForBuild\.(bat|cmd)\Z'
吗?
要添加到@user3303020 答案并将搜索结果输出到文件中,您可以运行
Get-ChildItem V:\MyFolder -name -recurse *.CopyForbuild.bat > path_to_results_filename.txt
以这种方式搜索正确的文件可能会更容易。
搜索所有带有 ext "py" 的文件,从 / 开始: dir -r *.py 或 dir *.py -r
cd V:\MyFolder
后跟ls -r -inc CopyForBuild.bat
ls -r -ea silentlycontinue -fo -inc "filename.txt" | % { $_.fullname }
filter
和inc
之间的差异。-fo
可能是force
。%
是foreach-object
的别名