更新时间:2022-11-27 19:58:39
这是一个可能的解决方案:
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 $_ }
}
请注意,这应该特别适用于您使用 Format-List
获得的那种输出,但不是一个经过深思熟虑的突出显示功能,否则:例如,这将无法处理可能在同一行文本中多次出现.
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: e.g this won't handle words that might appear multiple times in the same line of text.
另外,仅供参考,以这种方式使用 PowerShell 通常不是***实践.您应该考虑编写输出到管道的 PowerShell 工具,而不是通过 Write-Host
,这样您就可以在其他命令中操作结果,或将其转换(例如,转换为 CSV 等).
Also FYI working with PowerShell in this way isn't generally best practice. 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 (e.g to CSV etc.).