什麼是PowerShell的DOS FINDSTR等價物?我需要搜索一堆日誌文件以查找「錯誤」。PowerShell FINDSTR eqivalent?
19
A
回答
23
0
7
例如,在此目錄中的c文件和所有子目錄中查找「#include」的所有實例。
gci -r -i *.c | select-string "#include"
GCI是GET-childitem
3
只是對Monroecheeseman的回答擴大的別名。 gci是Get-ChildItem的別名(相當於dir或ls),-r開關執行遞歸搜索,-i代表include。
將該查詢的結果管道化爲select-string,它讀取每個文件並查找與正則表達式匹配的行(本例中提供的行是ERROR,但它可以是任何.NET正則表達式)。
結果將是匹配對象的集合,顯示行匹配,文件和其他相關信息。
0
在相關說明中,這裏是一個搜索,它將列出包含特定正則表達式搜索或字符串的所有文件。它可以使用一些改進,所以隨時可以使用它。另外如果有人想將它封裝在一個值得歡迎的函數中。
我在這裏是新的,所以如果這應該在它自己的話題只是讓我知道。我想我會把它放在她身上,因爲這看起來大部分都是相關的。
# Search in Files Script
# ---- Set these before you begin ----
$FolderToSearch="C:\" # UNC paths are ok, but remember you're mass reading file contents over the network
$Search="Looking For This" # accepts regex format
$IncludeSubfolders=$True #BUG: if this is set $False then $FileIncludeFilter must be "*" or you will always get 0 results
$AllMatches=$False
$FileIncludeFilter="*".split(",") # Restricting to specific file types is faster than excluding everything else
$FileExcludeFilter="*.exe,*.dll,*.wav,*.mp3,*.gif,*.jpg,*.png,*.ghs,*.rar,*.iso,*.zip,*.vmdk,*.dat,*.pst,*.gho".split(",")
# ---- Initialize ----
if ($AllMatches -eq $True) {[email protected]{AllMatches=$True}}
else {[email protected]{List=$True}}
if ($IncludeSubfolders -eq $True) {[email protected]{Recurse=$True}}
else {[email protected]{Recurse=$False}}
# ---- Build File List ----
#$Files=Get-Content -Path="$env:userprofile\Desktop\FileList.txt" # For searching a manual list of files
Write-Host "Building file list..." -NoNewline
$Files=Get-ChildItem -Include $FileIncludeFilter -Exclude $FileExcludeFilter -Path $FolderToSearch -ErrorAction silentlycontinue @RecurseParam|Where-Object{-not $_.psIsContainer} # @RecurseParam is basically -Recurse=[$True|$False]
#$Files=$Files|Out-GridView -PassThru -Title 'Select the Files to Search' # Manually choose files to search, requires powershell 3.0
Write-Host "Done"
# ---- Begin Search ----
Write-Host "Searching Files..."
$Files|
Select-String $Search @SelectParam| #The @ instead of $ lets me pass the hastable as a list of parameters. @SelectParam is either -List or -AllMatches
Tee-Object -Variable Results|
Select-Object Path
Write-Host "Search Complete"
#$Results|Group-Object path|ForEach-Object{$path=$_.name; $matches=$_.group|%{[string]::join("`t", $_.Matches)}; "$path`t$matches"} # Show results including the matches separated by tabs (useful if using regex search)
<# Other Stuff
#-- Saving and restoring results
$Results|Export-Csv "$env:appdata\SearchResults.txt" # $env:appdata can be replaced with any UNC path, this just seemed like a logical place to default to
$Results=Import-Csv "$env:appdata\SearchResults.txt"
#-- alternate search patterns
$Search="(\d[-|]{0,}){15,19}" #Rough CC Match
#>
0
這不是做到這一點的最好辦法:
gci <the_directory_path> -filter *.csv | where { $_.OpenText().ReadToEnd().Contains("|") -eq $true }
幫我找到它有|
字符,將它們所有CSV文件。
0
PowerShell已基本排除findstr.exe的需要,如前面的答案所示。任何這些答案都應該可以正常工作。
但是,如果您實際上需要使用findstr,則需要使用。EXE(因爲是我的情況),這裏是一個PowerShell的包裝吧:
使用-Verbose
選項輸出FINDSTR命令行。
function Find-String
{
[CmdletBinding(DefaultParameterSetName='Path')]
param
(
[Parameter(Mandatory=$true, Position=0)]
[string]
$Pattern,
[Parameter(ParameterSetName='Path', Mandatory=$false, Position=1, ValueFromPipeline=$true)]
[string[]]
$Path,
[Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias('PSPath')]
[string[]]
$LiteralPath,
[Parameter(Mandatory=$false)]
[switch]
$IgnoreCase,
[Parameter(Mandatory=$false)]
[switch]
$UseLiteral,
[Parameter(Mandatory=$false)]
[switch]
$Recurse,
[Parameter(Mandatory=$false)]
[switch]
$Force,
[Parameter(Mandatory=$false)]
[switch]
$AsCustomObject
)
begin
{
$value = $Pattern.Replace('\', '\\\\').Replace('"', '\"')
$findStrArgs = @(
'/N'
'/O'
@('/R', '/L')[[bool]$UseLiteral]
"/c:$value"
)
if ($IgnoreCase)
{
$findStrArgs += '/I'
}
function GetCmdLine([array]$argList)
{
($argList | foreach { @($_, "`"$_`"")[($_.Trim() -match '\s')] }) -join ' '
}
}
process
{
$PSBoundParameters[$PSCmdlet.ParameterSetName] | foreach {
try
{
$_ | Get-ChildItem -Recurse:$Recurse -Force:$Force -ErrorAction Stop | foreach {
try
{
$file = $_
$argList = $findStrArgs + $file.FullName
Write-Verbose "findstr.exe $(GetCmdLine $argList)"
findstr.exe $argList | foreach {
if (-not $AsCustomObject)
{
return "${file}:$_"
}
$split = $_.Split(':', 3)
[pscustomobject] @{
File = $file
Line = $split[0]
Column = $split[1]
Value = $split[2]
}
}
}
catch
{
Write-Error -ErrorRecord $_
}
}
}
catch
{
Write-Error -ErrorRecord $_
}
}
}
}
相關問題
- 1. (powershell)選擇字符串與Findstr
- 2. VisualStudio的eqivalent到ARM的#pragma anon_unions
- 3. 使用FINDSTR
- 4. DOS命令FINDSTR
- 5. FINDSTR結腸困惑?
- 6. 管道FINDSTR輸出
- 7. Powershell遠程DIR/findstr命令排除臨時互聯網文件夾
- 8. findstr中的正則表達式
- 9. findstr中的轉義引號
- 10. CMD Findstr工具用ping
- 11. FindStr不能正常工作
- 12. 將FindStr輸出到變量
- 13. findstr正則表達式
- 14. Findstr命令提示符
- 15. FINDSTR拒絕匹配EOL
- 16. 管道到findstr的輸入
- 17. grep像語法與findstr
- 18. 在findstr中使用正則表達式
- 19. Findstr獲取變量的響應
- 20. 命令提示符中的FINDSTR
- 21. 使用FINDSTR搜索未知的IP
- 22. 緩慢處理循環,利用findstr
- 23. Findstr工具/ g的令牌或DELIM
- 24. FINDSTR沒有找到「主頁」:「http://www.google.com/」
- 25. 使用findstr執行管道命令
- 26. 如何運行聯合findstr腳本
- 27. Findstr查找字符串並打印出
- 28. windows批處理文件:psexec和findstr
- 29. FINDSTR和正則表達式問題
- 30. 如何使用findstr獲取MAC地址?
有一個很好的文章,這樣的網站:http://www.interact-sw.co.uk/iangblog/2006/06/03/pshfindstr – 2008-08-18 14:45:08