Search PowerShell FINDSTR eqivalent?
DOS FINDSTR的等价物是什么?我需要在一堆日志文件中搜索“错误”。以下是快速答案Search PowerShell FINDSTR eqivalent?,search,powershell,Search,Powershell,DOS FINDSTR的等价物是什么?我需要在一堆日志文件中搜索“错误”。以下是快速答案 Get-ChildItem -Recurse -Include *.log | select-string ERROR 我找到了一个非常深刻的答案 if ($entry.EntryType -eq "Error") 由于是面向对象的,您希望使用您可以找到的标准比较运算符之一测试有问题的属性 我现在有一个远程监视日志的程序-一些简单的修改应该可以让它为您工作 编辑:我想我还应该补充一点,如果您不想像我那
Get-ChildItem -Recurse -Include *.log | select-string ERROR
我找到了一个非常深刻的答案
if ($entry.EntryType -eq "Error")
由于是面向对象的,您希望使用您可以找到的标准比较运算符之一测试有问题的属性
我现在有一个远程监视日志的程序-一些简单的修改应该可以让它为您工作
编辑:我想我还应该补充一点,如果您不想像我那样展开,那么这已经是为此构建的cmdlet了。退房:
man Get-EventLog
Get-EventLog -newest 5 -logname System -EntryType Error
例如,在此目录和所有子目录中的c文件中查找“#include”的所有实例
gci -r -i *.c | select-string "#include"
gci是get childitem的别名,只是为了扩展Monroecheseman的答案。gci是Get ChildItem(相当于dir或ls)的别名,-r开关执行递归搜索,-i表示include 将查询结果管道化为select string,让它读取每个文件并查找与正则表达式匹配的行(本例中提供的是ERROR,但可以是任何.NET正则表达式)
结果将是一个匹配对象的集合,显示行匹配、文件和其他相关信息。在相关注释中,这里的搜索将列出包含特定正则表达式搜索或字符串的所有文件。它可能需要一些改进,所以请随意操作。如果有人想把它封装在一个受欢迎的函数中 我是新来的,所以如果这是我自己的话题,请告诉我。我想我应该把它放在她身上,因为这看起来很有关系
# 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
#>
#在脚本文件中搜索
#----在开始之前设置这些--
$FolderToSearch=“C:\”\UNC路径是可以的,但请记住,您正在通过网络大量读取文件内容
$Search=“查找此”#接受正则表达式格式
$IncludeSubfolders=$True#BUG:如果设置为$False,则$FileIncludeFilter必须为“*”,否则将始终得到0个结果
$AllMatches=$False
$FileIncludeFilter=“*”.split(“,”)#限制特定的文件类型比排除所有其他文件类型更快
$FileExcludeFilter=“*.exe、*.dll、*.wav、*.mp3、*.gif、*.jpg、*.png、*.ghs、*.rar、*.iso、*.zip、*.vmdk、*.dat、*.pst、*.gho”。拆分(“,”)
#----初始化----
如果($AllMatches-eq$True){$SelectParam=@{AllMatches=$True}
else{$SelectParam=@{List=$True}
如果($IncludeSubfolders-eq$True){$RecurseParam=@{Recurse=$True}
else{$RecurseParam=@{Recurse=$False}
#----生成文件列表----
#$Files=Get Content-Path=“$env:userprofile\Desktop\FileList.txt”#用于搜索手动文件列表
写入主机“构建文件列表…”-非脱机
$Files=Get ChildItem-Include$FileIncludeFilter-Exclude$FileExcludeFilter-Path$FolderToSearch-ErrorAction silentlycontinue@RecurseParam |其中对象{-not$\uuz.psIsContainer}#@RecurseParam基本上是-Recurse=[$True |$False]
#$Files=$Files | Out GridView-PassThru-Title“选择要搜索的文件”#手动选择要搜索的文件,需要powershell 3.0
写主机“完成”
#----开始搜索----
写主机“搜索文件…”
$Files|
选择字符串$Search@SelectParam |#将@替换为$使我可以将hastable作为参数列表传递@SelectParam为-List或-AllMatches
Tee对象-变量结果|
选择对象路径
写入主机“搜索完成”
#$Results | Group Object path | ForEach Object{$path=$\.name;$matches=$\.Group |%{[string]::join(`t',$\.matches)};“$path`t$matches”}显示结果,包括由制表符分隔的匹配项(如果使用正则表达式搜索,则很有用)
这不是最好的方法:
gci <the_directory_path> -filter *.csv | where { $_.OpenText().ReadToEnd().Contains("|") -eq $true }
gci-filter*.csv |其中{$\.OpenText().ReadToEnd()包含(“|”)eq$true}
这帮助我找到了所有包含
|字符的csv文件。PowerShell基本上不需要findstr.exe,如前面的答案所示。这些答案中的任何一个都应该很好
但是,如果您确实需要使用findstr.exe(就像我的情况一样),这里有一个PowerShell包装器:
使用-Verbose
选项输出findstr命令行
供参考:
如果您更新到Powershell版本7,则可以使用grep。。。
我知道egrep在Azure CLI上的powershell中。。。
但是SS在那里!
这里有一篇老文章:[https://devblogs.microsoft.com/powershell/select-string-and-grep/]有一个网站提供了一篇很好的文章:
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 $_
}
}
}
}