有没有办法显示符合 PowerShell 条件的文本行

Is there a way to display the lines of text that meets a condition with PowerShell

$data = Select-String -Path $selectedDirectory$sqlFile -Pattern "GRANT" -Context 5,5

我想使用 PowerShell 读取 .SQL 文件,我们想确保用户不会在没有人工检查文件以查看是否正常的情况下使用 GRANT、DROP 或 DELETE。

我的第 1 行只查看 GRANT,但我认为它不起作用。

如果关键字在文件中,我想在屏幕上显示文本的一部分 +/- 5 行,即发现违规文本的位置。

有没有办法更改具有违规搜索条件的特定行的文本颜色(所有其他行将显示为默认值)

首先,"GRANT" 应该放在引号中以表示一个字符串。

如果您注意到,$line = Select-String -Pattern "Grant" 将 return 一个对象。

如果您使用 Get-Member 查看对象的属性,其中之一是 LineNumber

如果您使用 $data = Get-Content File.sql 或任何类似的方式读取了文件的内容,您将拥有作为数组对象的数据。现在您可以使用此行号提取 +/- 5 行,如您所愿 $data[50..60]。这将显示从第 50 行到第 60 行的输出行。您可以轻松地将 50 和 60 替换为您的变量。

如果你想在控制台上显示颜色,你需要使用Write-Host

$data = Select-String -Path $selectedDirectory$sqlFile -Pattern "GRANT|DROP|DELETE" -Context 5,5
$data | Foreach-Object {
    $_.Context.Precontext
    Write-Host $_.Line -ForeGroundColor Cyan
    $_.Context.Postcontext
}

我会试一试。

此函数获取一个文件,搜索那些关键字,然后打印 +/- 5 行。它非常简单,我相信您知道它是如何工作的以及如何修改它。您可以找到 matchinfo class 的参考(由 Select-String( here.

返回
Function Get-SQLForbiddenWords ($sqlDataFile) {
    $data =  Select-String -Path $sqlDataFile -Pattern "GRANT|DROP|DELETE" 
    Foreach ( $line in $data) {
        $lineNumberS = $line.LineNumber - 5
        $lineNumberE = $line.LineNumber + 5
        echo ('Bad Command Detected: {0}' -f $line.line)
        (Get-Content $sqlDataFile)[$lineNumberS..$lineNumberE]
        echo "`n"
    }
}

非常有趣。输出:

Bad Command Detected: DROP
this is the sixth line 
GRANT
this is the seventh line
this is the eighth line
DROP
this is the ninth line 
this is the tenth linet
this is the eleventh line 
this is the twelfbthfbth line 

另一种方法是使用oss函数(=Out-String -Stream)。

Select-String "\b(GRANT|DROP|DELETE)\b" .\test.txt -Context 5 | oss | foreach { Write-Host $_ -ForegroundColor ("White","Cyan")[$_[0] -eq '>'] }

以下内容可能会使其更具可读性。

Select-String "\b(GRANT|DROP|DELETE)\b" .\test.txt -Context 5 | Out-String -Stream | foreach {
    if(-not $_) { return }
    $fileName,$lineNumber,$line = $_.Split(":", 3)
    $color = if($_.StartsWith(">")) { "Cyan" } else { "White" }
    Write-Host $fileName $lineNumber.PadLeft(3, "0") $line -ForegroundColor $color -Separator "  "
}