我正在运行下面的代码,它可以工作。我想做的是,在Enabled属性为True的结果中,我希望文本'True'前景色为绿色,否则为'false'为红色。
与“密码永不过期”属性相同,如果结果为“ True”,我希望文本“ True”的前景色为红色,否则为“ False”的绿色。
我试图将if-else语句放入代码中,但没有成功。
码:
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
Run Code Online (Sandbox Code Playgroud)
有什么建议么?
这是一个可能的解决方案:
$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 $_ }
}
Run Code Online (Sandbox Code Playgroud)
请注意,这应该特别适用于您获得的那种输出Format-List,但不是一个经过深思熟虑的突出显示功能,否则:例如,这不会处理可能在同一行文本中多次出现的单词。
另外仅供参考,以这种方式使用 PowerShell 通常不是最佳实践。您应该考虑编写输出到管道而不是通过 PowerShell 的工具,Write-Host这样您就可以在其他命令中操作结果,或将其转换(例如转换为 CSV 等)。
小智 5
使用此链接Format-Color中的函数以及与您的行匹配的正则表达式。
$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'}
Run Code Online (Sandbox Code Playgroud)
在下面找到高级功能Out-HostColored,您可以在其上传递任何命令并根据正则表达式/ substring选择性地为其输出着色。
通过模拟输入应用于您的案例:
@'
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
Run Code Online (Sandbox Code Playgroud)
传递单个正则表达式,该正则表达式仅匹配感兴趣的标记并将它们标记为绿色。
请注意,使用后置断言((?<=...))来匹配适当的上下文,而不将其包含在匹配中。
以上收益:
Out-HostColored 特征:
您可以通过管道传递任何命令-无论您依靠其隐式格式还是首先将其Format-*显式传递给cmdlet。
一次只能将匹配项限制为一行,但是支持为给定行的多个匹配项着色。
如果需要,可以显式指定前景色(-ForegroundColor)和(-BackgroundColor)。默认情况下,匹配项显示为绿色。
如果找到匹配项,则为整个行着色,通过 -WholeLine
要传递文字字符串以匹配而不是正则表达式,请传递-SimpleMatch。
Out-HostColored 源代码(PSv2 +):<#
.SYNOPSIS
Colors portions of the default host output that match a pattern.
.DESCRIPTION
Colors portions of the default-formatted host output based on either a
regular expression or a literal substring, 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.
.PARAMETER Pattern
The regular expression specifying what portions of the input should be
colored. Do not use named capture groups in the regular expression, unless you
also specify -WholeLine.
If -SimpleMatch is also specified, the pattern is interpreted as a literal
substring to match.
.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 as a literal substring to match rather than
as a regular expression.
.PARAMETER InputObject
Specifies what to output. Typically, the output form a command 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 '\bSeptember\b' red white
Outputs the current date with the word 'September' printed in red on a white background, if present.
#>
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.
try {
$re = [regex] ('(?<sep>{0})' -f $(if ($SimpleMatch) { [regex]::Escape($Pattern) } else { $Pattern }))
} 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.
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 ($havePattern -and $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.
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13780 次 |
| 最近记录: |