如何在powershell输出中应用颜色 [英] How to apply colors in powershell output

查看:53
本文介绍了如何在powershell输出中应用颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要求:

我是 PowerShell 的初学者.下面的 ps 脚本提供了有关服务处于启动状态或停止状态的详细信息,但我的要求是我需要将此输出作为天蓝色"中的背景颜色查看,如果服务正在运行,则以绿色突出显示,以红色突出显示停止的服务颜色.我如何实现它.

I am beginner in powershell. Below ps script is giving the details about services are in started state or in stopped state but my requirement is I need to see this out put as background color in 'Sky Blue', if services are running then highlight in Green ,Stopped services in Red color. How do I achieve it.

这方面的帮助非常有用.

Help on this is highly appriciated.

$Result = @() 
foreach($server in Get-Content C:\PowerSQL\List.txt) 
{ 
$Services=gwmi win32_service -computername $server | where {$_.Name -like ‘*SQL*’} 
if(!(Test-Connection -Cn $server -BufferSize 16 -Count 1 -ea 0 -quiet)) 
{"Problem still exists in connecting to $server"} 
ELSE { 
$services | ForEach { 
If ($_) 
{ $Result += New-Object PSObject -Property @{ 

‘Host Name’ = $_.Systemname 
‘Service Display Name’ = $_.Displayname 
‘Service Name’ = $_.Name 
‘Start Mode’ = $_.Startmode 
‘Service Account Name’ = $_.Startname 
‘State’ = $_.State 
‘Status’= $_.Status 
 } 
} 
} 
} 
} 

$Result | ConvertTo-HTML | Out-File C:\PowerSQL\service.htm 

推荐答案

请参阅我的回答对此类似问题.

Communary.ConsoleExtensions [link] 可能对您有所帮助

Communary.ConsoleExtensions [link] might help you

Invoke-ColorizedFileListing C:\Windows -m *.dmp

上述命令将对文件类型进行着色并突出显示转储文件.

The above command will colorise file types and highlight dump files.

要保存颜色输出,您必须保存为保留颜色的格式,如 RTF 或 HTML.txt(纯文本文件)只存储文本.

To save a color output, you would have to save to a format that preserves color, like RTF, or HTML. Txt (plain text file) only stores text.

下面的代码会将您的输出保存为 html 文件.

The code below will save your output as an html file.

$time = (Get-Date).AddYears(-2)
Get-ChildItem -Recurse | Where-Object {$_.LastWriteTime -lt $time} |
Select Directory,Name,LastWriteTime |
ConvertTo-Html -Title "Services" -Body "<H2>The result of Get-ChildItem</H2> " -Property Directory,Name,LastWriteTime |
ForEach-Object {
  if ($_ -like '<tr><td>*') {
    $_ -replace '^(.*?)(<td>.*?</td>)<td>(.*?)</td>(.*)','$1$2<td><font color="green">$3</font></td>$4'
  } else {
    $_
  }
} | Set-Content "$env:TEMP\ColorDirList.html" -Force

行:

if ($_ -like '<tr><td>*') {

...检查 html 输出中作为表格行的行.

...checks for line in the html output that is a table row.

行:

$_ -replace '^(.*?)(<td>.*?</td>)<td>(.*?)</td>(.*)','$1$2<td><font color="green">$3</font></td>$4'

...使用正则表达式将第二个表格单元格内容替换为绿色字体标记.这是一个非常简单的正则表达式搜索&替换只会为第二列着色.

...uses a RegEx to replace the 2nd table cell contents with a font tag with the color green. This is a very simple RegEx search & replace that will only color the 2nd column.

这是仅控制台着色的另一种实现,基于这个链接

And here's another implementation of console only coloring, based on this link

$linestocolor = @(
'CSName         Version        OSArchitecture'
'------         -------        --------------'
'BENDER         6.1.7601       64-bit        '
'LEELA          6.1.7601       64-bit        '
'FRY            6.1.7600       64-bit        '
'FARNSWORTH     6.1.7601       32-bit        '
)


# http://www.bgreco.net/powershell/format-color/
function Format-Color {
    [CmdletBinding()]
    param(
      [Parameter(ValueFromPipeline=$true,Mandatory=$true)]
      $ToColorize
    , [hashtable]$Colors=@{}
    , [switch]$SimpleMatch
    , [switch]$FullLine
    )
  Process {
    $lines = ($ToColorize | Out-String).Trim() -replace "`r", "" -split "`n"
    foreach($line in $lines) {
      $color = ''
      foreach($pattern in $Colors.Keys){
        if     (!$SimpleMatch -and !$FullLine -and $line -match "([\s\S]*?)($pattern)([\s\S]*)") { $color = $Colors[$pattern] }
        elseif (!$SimpleMatch -and $line -match $pattern) { $color = $Colors[$pattern] }
        elseif ($SimpleMatch -and $line -like $pattern) { $color = $Colors[$pattern] }
      }
      if ($color -eq '') { Write-Host $line }
        elseif ($FullLine -or $SimpleMatch) { Write-Host $line -ForegroundColor $color }
        else {
        Write-Host $Matches[1] -NoNewline
        Write-Host $Matches[2] -NoNewline -ForegroundColor $color
        Write-Host $Matches[3]
      }
    }
  }
}

$linestocolor | Format-Color -Colors @{'6.1.7600' = 'Red'; '32-bit' = 'Green'}

# doesn't work...
# (Get-ChildItem | Format-Table -AutoSize) | Format-Color -Colors @{'sql' = 'Red'; '08/07/2016' = 'Green'}
# does work...
Format-Color -ToColorize (Get-ChildItem | Format-Table -AutoSize) -Colors @{'sql' = 'Red'; '08/07/2016' = 'Green'}

return

编辑.回答 OP 请求

$Result = @()
foreach($server in Get-Content C:\PowerSQL\List.txt)
{
  $Services=gwmi win32_service -computername $server | where {$_.Name -like ‘*SQL*’}
  if(!(Test-Connection -Cn $server -BufferSize 16 -Count 1 -ea 0 -quiet))
    {"Problem still exists in connecting to $server"}
  else {
    $services | ForEach {
      If ($_)
        { $Result += New-Object PSObject -Property @{
        HostName = $_.Systemname
        ServiceDisplayName = $_.Displayname
        ServiceName = $_.Name
        StartMode = $_.Startmode
        ServiceAccountName = $_.Startname
        State = $_.State
        Status = $_.Status
        }
      }
    }
  }
} 

$Result | ConvertTo-HTML `
  -Title "Services" `
  -Body "<H2>The result of gwmi win32_service</H2> " `
  -Property HostName,ServiceDisplayName,ServiceName,StartMode,ServiceAccountName,State,Status |
ForEach-Object {
  if ($_ -like '<tr><td>*') {
    switch ($_) {
      { $_ -like '*<td>Stopped</td>*' } {$color='red'}
      { $_ -like '*<td>Running</td>*' } {$color='green'}
      Default                           {$color='white'}
    }
  $_.Replace('<tr>', "<tr bgcolor=`"$color`">")
  } else {
  $_
  }
} | Set-Content C:\PowerSQL\service.htm -Force

这篇关于如何在powershell输出中应用颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆