Color words in powershell script format-table output

后端 未结 4 2042
梦如初夏
梦如初夏 2021-01-12 11:03

Is it possible to color only certain words (not complete lines) for a powershell output using format-table. For example, this script scans a folder recursively for a string

4条回答
  •  耶瑟儿~
    2021-01-12 11:37

    I like Rynant's approach. Here is an alternate implementation, using -split instead of 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
    }
    

    Split includes empty strings if the line starts or ends with the given word, hence the extra "if not first" logic.


    Edit: Following Rynant's comment, here's another implementation that supports both simple and regex patterns:

    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
    }
    

    The output from the following examples shows the difference:

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

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

提交回复
热议问题