powershell脚本格式表输出中的颜色词

Eti*_*neT 7 powershell powershell-2.0

是否可以使用format-table为powershell输出仅为某些单词(不是完整的行)着色.例如,此脚本以递归方式扫描文件夹以查找字符串,然后使用format-table输出结果.

dir -r -i *.* | Select-String $args[0] |
format-table -Property @{label="Line #"; Expression={$_.LineNumber}; width=6},
Path, Line -wrap
Run Code Online (Sandbox Code Playgroud)

能够使用特定颜色格式化我们正在搜索的单词会很好,这样您就可以准确地看到它在线上的位置.

Ryn*_*ant 14

你可以管表入里Out-String,然后写在使用部分字符串Write-Host-NoNewLine开关.

像这样的东西:

filter ColorWord {
    param(
        [string] $word,
        [string] $color
    )
    $line = $_
    $index = $line.IndexOf($word, [System.StringComparison]::InvariantCultureIgnoreCase)
    while($index -ge 0){
        Write-Host $line.Substring(0,$index) -NoNewline
        Write-Host $line.Substring($index, $word.Length) -NoNewline -ForegroundColor $color
        $used = $word.Length + $index
        $remain = $line.Length - $used
        $line = $line.Substring($used, $remain)
        $index = $line.IndexOf($word, [System.StringComparison]::InvariantCultureIgnoreCase)
    }
    Write-Host $line
}

Get-Process| Format-Table| Out-String| ColorWord -word 1 -color magenta
Run Code Online (Sandbox Code Playgroud)

  • 效果很好!修改了这一行:$ index = $ line.IndexOf($ word)to $ index = $ line.IndexOf($ word,[System.StringComparison] :: InvariantCultureIgnoreCase) (2认同)

Emp*_*LII 5

我喜欢Rynant的方法.这是一个替代实现,使用-split而不是IndexOf:

filter ColorWord( [string]$word, [ConsoleColor]$color ) {
    $later = $false
    $_ -split [regex]::Escape( $word ) | foreach {
      if( $later ) { Write-Host "$word" -NoNewline -ForegroundColor $color }
      else { $later = $true }
      Write-Host $_ -NoNewline
    }
    Write-Host
}
Run Code Online (Sandbox Code Playgroud)

如果行以给定单词开头或结尾,则Split包括空字符串,因此额外的"if not first"逻辑.


编辑:按照Rynant的评论,这是另一个支持简单和正则表达式模式的实现:

filter ColorPattern( [string]$Pattern, [ConsoleColor]$Color, [switch]$SimpleMatch ) {
  if( $SimpleMatch ) { $Pattern = [regex]::Escape( $Pattern ) }

  $split = $_ -split $Pattern
  $found = [regex]::Matches( $_, $Pattern, 'IgnoreCase' )
  for( $i = 0; $i -lt $split.Count; ++$i ) {
    Write-Host $split[$i] -NoNewline
    Write-Host $found[$i] -NoNewline -ForegroundColor $Color
  }

  Write-Host
}
Run Code Online (Sandbox Code Playgroud)

以下示例的输出显示了不同之处:

PS> '\d00\d!' | ColorPattern '\d' 'Magenta' -Simple
\d00\d!

PS> '\d00\d!' | ColorPattern '\d' 'Magenta'
\d00\d!