PowerShell的DOS FINDSTR等价物是什么?我需要搜索一堆日志文件“ERROR”。
答案 0 :(得分:26)
答案 1 :(得分:7)
例如,在此目录和所有子目录的c文件中查找“#include”的所有实例。
gci -r -i *.c | select-string "#include"
gci是get-childitem的别名
答案 2 :(得分:3)
只是为了扩展Monroecheeseman的答案。 gci是Get-ChildItem的别名(相当于dir或ls),-r开关执行递归搜索,-i表示包含。
将该查询的结果管道化为select-string使其读取每个文件并查找与正则表达式匹配的行(在这种情况下提供的行是ERROR,但它可以是任何.NET正则表达式)。
结果将是匹配对象的集合,显示行匹配,文件和其他相关信息。
答案 3 :(得分:0)
if ($entry.EntryType -eq "Error")
面向对象,您希望使用可以找到here的标准比较运算符来测试相关属性。
我现在有一个PS script远程监视日志 - 一些简单的修改应该让它适合你。
编辑:我想我还应该添加一个为此而构建的cmdlet,如果你不想以我的方式展开它。退房:
man Get-EventLog
Get-EventLog -newest 5 -logname System -EntryType Error
答案 4 :(得分: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) {$SelectParam=@{AllMatches=$True}}
else {$SelectParam=@{List=$True}}
if ($IncludeSubfolders -eq $True) {$RecurseParam=@{Recurse=$True}}
else {$RecurseParam=@{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
#>
答案 5 :(得分:0)
这不是最好的方法:
gci <the_directory_path> -filter *.csv | where { $_.OpenText().ReadToEnd().Contains("|") -eq $true }
这有助于我找到所有csv文件,其中包含|
个字符。
答案 6 :(得分: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 $_
}
}
}
}
答案 7 :(得分:0)
仅供参考: 如果您更新到Powershell版本7,则可以使用grep ... 我知道egrep在Azure CLI的powershell中... 但是SS在那里! 此处的旧文章:[https://devblogs.microsoft.com/powershell/select-string-and-grep/]