简体   繁体   English

Powershell - 某些结果的输出颜色

[英]Powershell - Output Color for certain results

I am running the code below and it works.我正在运行下面的代码并且它有效。 What I am trying to do is, in the results when Enabled properties is True I would like to the text 'True' foreground color to be green otherwise if 'false' color Red.我想要做的是,在启用属性为 True 时的结果中,我希望文本“真”前景色为绿色,否则如果“假”颜色为红色。

The same with the Password never expires properties, if the result is 'True' I would like to the text 'True' foreground color to be Red otherwise if its 'False' color green.与 Password never expires 属性相同,如果结果为“True”,我希望文本“True”前景色为红色,否则如果其“False”颜色为绿色。

I am trying to fit an if-else statement into the code but have not been successfull.我正在尝试将 if-else 语句放入代码中,但没有成功。

Code:代码:

Get-ADUser "user name"  -Properties Enabled,LockedOut,DisplayName,GivenName, SurName,Mail,LastLogon, Created,passwordlastset,Passwordneverexpires,msDS-UserPasswordExpiryTimeComputed, Description, office, Canonicalname | `
        Select-Object Enabled, 
        @{Expression={$_.LockedOut};Label='Locked';}, 
        @{Expression={$_.DisplayName};Label='Display Name';},
        @{Expression ={$_.GivenName};Label='Name';}, `
        @{Expression ={$_.SurName}; Label='Last Name'; }, 
        Mail, 
        @{Expression ={[DateTime]::FromFileTime($_.LastLogon)}; Label='Last Logon';}, 
        @{Expression={$_.Created};Label='Date Created';}, 
        @{Expression={$_.passwordlastset};Label='PW Last Reset';}, 
        @{Expression={$_.Passwordneverexpires};Label='PW Never Expires';},
        @{Name="PW Exp Date";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}}  ,
        Description, 
        Office,
        Canonicalname 
        Format-list

在此处输入图片说明

Any suggestions?有什么建议吗?

Find advanced function Out-HostColored below, to which you can pipe any command and color its output selectively based on regular expressions / literal substrings . Out-HostColored下面找到高级函数Out-HostColored ,您可以将任何命令传送到该函数,并根据正则表达式/文字子字符串有选择地为其输出着色

Applied to your case, with simulated input:应用于您的案例,模拟输入:

@'
Enabled          : True
Locked           : False
Display Name     : foo
Name             : bar
Last Name        : baz
Mail             : bar.baz@example.org
Last Logon       : 9/1/2017 7:33:30 PM
Date Created     : 11/21/2014 6:04:54 AM
PW Last Reset    : 9/2/2015
PW Never Expires : False
Description      : Technician
Office           : IT
Canonical Name   : CORPORATE.LOCAL/foo Users/bar
'@ |
  Out-HostColored '(?<=Enabled\s+: )True', '(?<=PW Never Expires\s+: )False' Green

Two regular expressions are passed that match only the tokens of interest and color them green Originally, only a single regex was supported.两个正则表达式是通过那场比赛唯一的兴趣,它们的颜色绿色令牌最初,只有一个正则表达式得到了支持。 Tip of the hat to @SamHasler for the suggestion to accept an array . @SamHasler建议接受数组 . .
Note the use of look-behind assertions ( (?<=...) ) to match the proper context without including it in the match.请注意使用后视断言 ( (?<=...) ) 来匹配正确的上下文,而不将其包含在匹配中。

The above yields:以上产生:

样本输出

Out-HostColored features: Out-HostColored特点:

  • You can pipe any command - whether you rely on its implicit formatting or whether you pipe it to a Format-* cmdlet explicitly first.您可以通过管道传输任何命令 - 无论您是依赖其隐式格式,还是首先将其显式传输到Format-* cmdlet。

  • Matching is restricted to a single line at a time, but coloring multiple matches on a given line is supported.一次只能匹配一行,但支持在给定的行上为多个匹配着色。

  • You can specify both a foreground color ( -ForegroundColor ) and ( -BackgroundColor ) explicitly if desired;您可以同时指定前景颜色( -ForegroundColor )和( -BackgroundColor如果需要明确); by default, matches are colored green.默认情况下,匹配项为绿色。

  • To color the entire line if a match is found, pass -WholeLine如果找到匹配项,要为整条线着色,请传递-WholeLine

  • To pass literal substrings to match rather than regular expressions, use -SimpleMatch .要传递文字子字符串以匹配而不是正则表达式,请使用-SimpleMatch


Out-HostColored source code (PSv2+): Out-HostColored源代码 (PSv2+):

Note:注意:

  • The function below is now also available as an MIT-licensed Gist - only the latter will be maintained going forward.下面的函数现在也可以作为MIT 许可的 Gist 使用- 只有后者将继续维护

  • The Gist additionally supports a -CaseSensitive switch and pattern-specific coloring , via a dictionary of per-pattern colors Tip of the hat to @not2qubit for the inspiration ; Gist支持-CaseSensitive开关和特定于模式的着色,通过每个模式颜色的字典提示@not2qubit获得灵感 eg:例如:

     # Prints "easy" and "green" in green, "being" in black on yellow. 'It ain''t easy being green.' | Out-HostColored @{ ('easy', 'green') = 'green' '\\bbe.+?\\b' = 'black,yellow' }
  • In PSv3+, you can install the function directly from the Gist as follows (while I personally assure you that doing so is safe, it's generally a good idea to check the source first):在 PSv3+ 中,您可以直接从 Gist 安装该功能,如下所示(虽然我个人向您保证这样做是安全的,但通常最好先检查源代码):

     irm https://gist.github.com/mklement0/243ea8297e7db0e1c03a67ce4b1e765d/raw/Out-HostColored.ps1 | iex
<#
.SYNOPSIS
Colors portions of the default host output that match given patterns.

.DESCRIPTION
Colors portions of the default-formatted host output based on either
regular expressions or a literal substrings, assuming the host is a console or
supports colored output using console colors.

Matching is restricted to a single line at a time, but coloring multiple
matches on a given line is supported.

Note: Since output is sent to the host rather than the pipeline, you cannot
      chain calls to this function.

.PARAMETER Pattern
One or more search patterns specifying what parts of the formatted 
representations of the input objects should be colored.

 * By default, these patterns are interpreted as regular expressions.

 * If -SimpleMatch is also specified, the patterns are interpreted as literal
   substrings.

.PARAMETER ForegroundColor
The foreground color to use for the matching portions.
Defaults to green.

.PARAMETER BackgroundColor
The optional background color to use for the matching portions.

.PARAMETER WholeLine
Specifies that the entire line containing a match should be colored,
not just the matching portion.

.PARAMETER SimpleMatch
Interprets the -Pattern argument(s) as a literal substrings to match rather
than as regular expressions.

.PARAMETER InputObject
The input object(s) whose formatted representations to color selectively.
Typically provided via the pipeline.

.NOTES
Requires PSv2 or above.
All pipeline input is of necessity collected first before output is produced.

.EXAMPLE
Get-Date | Out-HostColored '\b\p{L}+\b' red white

Outputs the current date with all words composed of letters (p{L}) only in red
on a white background.

.EXAMPLE
Get-ChildItem | select Name | Out-HostColored -WholeLine -SimpleMatch .exe

Highlight all executable file names in green.

.EXAMPLE
'apples', 'kiwi', 'pears' | Out-HostColored '^a', 's$' blue

Highlight all As at the beginning and Ss at the end of lines in blue.
#>
Function Out-HostColored {
  # Note: The [CmdletBinding()] and param() block are formatted to be PSv2-compatible.
  [CmdletBinding()]
  param(
    [Parameter(Position = 0, Mandatory = $True)] [string[]] $Pattern,
    [Parameter(Position = 1)] [ConsoleColor] $ForegroundColor = 'Green',
    [Parameter(Position = 2)] [ConsoleColor] $BackgroundColor,
    [switch] $WholeLine,
    [switch] $SimpleMatch,
    [Parameter(Mandatory = $True, ValueFromPipeline = $True)] $InputObject
  )

  # Wrap the pattern / literal in an explicit capture group.
  # Fail, if the given regex is syntactically invalid.
  try {
    $re = [regex] ('(?<sep>{0})' -f $(if ($SimpleMatch) { 
          ($Pattern | ForEach-Object { [regex]::Escape($_) }) -join '|'
        } 
        else { 
          ($Pattern | ForEach-Object { '(?:{0})' -f $_ }) -join '|'
        }))
  }
  catch { Throw }

  # Build a parameters hashtable specifying the colors, to be use via
  # splatting with Write-Host later.
  $htColors = @{
    ForegroundColor = $ForegroundColor
  }
  if ($BackgroundColor) {
    $htColors.Add('BackgroundColor', $BackgroundColor)
  }

  # Use pipeline input, if provided (the typical case).
  if ($MyInvocation.ExpectingInput) { $InputObject = $Input }

  # Apply default formatting to each input object, and look for matches to
  # color line by line.
  $InputObject | Out-String -Stream | ForEach-Object {
    $line = $_
    if ($WholeLine) {
      # Color the whole line in case of match.
      if ($line -match $re) {
        Write-Host @htColors $line
      }
      else {
        Write-Host $line
      }
    }
    else {
      # Split the line by the regex and include what the regex matched.
      $segments = $line -split $re, 0, 'ExplicitCapture'
      if ($segments.Count -eq 1) {
        # no matches -> output line as-is
        Write-Host $line
      }
      else {
        # at least 1 match, as a repeating sequence of <pre-match> - <match> pairs
        $i = 0
        foreach ($segment in $segments) {
          if ($i++ % 2) {
            # matching part
            Write-Host -NoNewline @htColors $segment
          }
          else {
            # non-matching part
            Write-Host -NoNewline $segment
          }
        }
        Write-Host '' # Terminate the current output line with a newline.
      }
    }
  }
}

Here's a possible solution:这是一个可能的解决方案:

$Highlight = @{
    True = 'Red'
    False = 'Green'
}

$User = Get-ADUser "user name"  -Properties Enabled,LockedOut,DisplayName,GivenName,SurName,Mail,LastLogon,Created,passwordlastset,Passwordneverexpires,msDS-UserPasswordExpiryTimeComputed, Description, office, Canonicalname |
        Select-Object Enabled, 
        @{Expression={$_.LockedOut};Label='Locked';}, 
        @{Expression={$_.DisplayName};Label='Display Name';},
        @{Expression ={$_.GivenName};Label='Name';}, `
        @{Expression ={$_.SurName}; Label='Last Name'; }, 
        Mail, 
        @{Expression ={[DateTime]::FromFileTime($_.LastLogon)}; Label='Last Logon';}, 
        @{Expression={$_.Created};Label='Date Created';}, 
        @{Expression={$_.passwordlastset};Label='PW Last Reset';}, 
        @{Expression={$_.Passwordneverexpires};Label='PW Never Expires';},
        @{Name="PW Exp Date";Expression={[datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")}},
        Description, 
        Office,
        Canonicalname | Format-list | Out-String

$User -split "`n" | ForEach-Object {
    $Output = $False
    If ($_ -match 'Enabled|PW Never Expires') {
        ForEach ($Entry in $Highlight.Keys){
            $Text = $_ -split $Entry
            If ($Text.count -gt 1) { 
                Write-Host $Text[0] -NoNewline
                Write-Host $Entry -ForegroundColor $Highlight.$Entry
                $Output = $true
                Break
            }
        }
    }

    If (-not $Output) { Write-Host $_ }
}

Note that this should work for the sort of output you get with Format-List in particular but isn't a particularly well thought out highlighting function otherwise: eg this won't handle words that might appear multiple times in the same line of text.请注意,这应该特别适用于您使用Format-List获得的那种输出,但不是特别经过深思熟虑的突出显示功能,否则:例如,这不会处理可能在同一行文本中多次出现的单词。

Also FYI working with PowerShell in this way isn't generally best practice.另外仅供参考,以这种方式使用 PowerShell 通常不是最佳实践。 You should consider writing PowerShell tools that output to the pipeline and not via Write-Host , that way you can manipulate the results in other commands, or transform it (eg to CSV etc.).您应该考虑编写输出到管道而不是通过Write-Host PowerShell 工具,这样您就可以在其他命令中操作结果,或将其转换(例如转换为 CSV 等)。

Use the function Format-Color from this link with a RegEx matching your lines.将此链接中的函数Format-Color与与您的行匹配的 RegEx 一起使用。

$String = @"
Enabled          : True
Locked           : False
Display Name     : empty
Last Logon       : 9/1/2017
PW Last Reset    : 9/2/2015
PW Never Expires : False
Description      : Technician
Offic            : IT
"@

$String  | Format-Color @{'^PW Never Expires\s+: False|^Enabled\s+: True' = 'Green'}

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM