我正在所有文件夹中搜索文件。
Copyforbuild.bat在很多地方都可以使用,我想递归搜索。
$File = "V:\Myfolder\**\*.CopyForbuild.bat"
如何在 PowerShell 中执行此操作?
我正在所有文件夹中搜索文件。
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}
您始终可以*在FolderNameand/or中使用通配符FileName.fileExtension。例如:
dir -Path C:\Folder* -Filter File*.file* -Recurse | %{$_.FullName}
上面的示例将搜索C:\驱动器中以单词开头的任何文件夹Folder。因此,如果您有一个名为的文件夹FolderFoo,FolderBarPowerShell 将显示这两个文件夹的结果。
文件名和文件扩展名也是如此。如果要搜索具有特定扩展名的文件,但不知道文件名,可以使用:
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 -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 $falsefor 目录。不要留下尾随通配符,例如bin/*.
为什么不使用内置开关?它们很糟糕,并且会随机删除功能。例如,为了-Include与文件一起使用,您必须以通配符结束路径。但是,这会在-Recurse不告诉您的情况下禁用开关:
Get-ChildItem -File -Recurse -Path ./bin/* -Include *.lib
你会认为这会给你*.lib所有子目录中的所有 s,但它只会搜索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"}
使用通配符过滤:
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' }
要添加到@user3303020 答案并将搜索结果输出到文件中,您可以运行
Get-ChildItem V:\MyFolder -name -recurse *.CopyForbuild.bat > path_to_results_filename.txt
以这种方式搜索正确的文件可能会更容易。
搜索所有带有 ext "py" 的文件,从 / 开始: dir -r *.py 或 dir *.py -r