tech.guitarrapc.cóm

Technical updates

PowerShellのWrite-Hostで色付きメッセージを出してみる

PowerShellでのホスト表示にはいくつかの方法があります。 その中で、ホスト表示色を自由に扱えるのが、Write-Hostコマンドレットです。

その利用例を見てみましょう。

Write-Host コマンドレット

Write-Hostコマンドレットには-ForeGroundColorパラメータと-BackGroundColorパラメータがあり、表示文字色、表示背景色を制御できます。 特に指定しなかった場合は、デフォルト色となります。

利用可能な色一覧:

Black
Blue
Cyan
DarkBlue
DarkCyan
DarkGray
DarkGreen
DarkMagenta
DarkRed
DarkYellow
Gray
Green
Magenta
Red
White
Yellow

例: 表示文字色をCyanとする

Write-Host "hogehoge cyan!!" -ForegroundColor Cyan

背景色も同様に変更可能です。

Write-Host "Gray top, yellow back!" -ForegroundColor Black -BackgroundColor Yellow

事前に定義する

psm1など、function内でちょくちょく使う場合は、事前に組み合わせを定義しておくのもいいでしょう。

function Get-WriteHostColourSplat{

  [CmdletBinding()]
  param(
  )

  Write-Verbose "Set Colour Splat Definition"
  # Create Colour Splats
  $green = @{ForegroundColor= "Green"}
  $white = @{ForegroundColor= "White"}
  $yellow = @{ForegroundColor= "Yellow"}
  $red = @{ForegroundColor= "red"}
  $cyan = @{ForegroundColor= "cyan"}

  Write-Verbose "Set Colour Splat variables for function scope."
  # Create Colour constants in the previous scope.
  New-Variable -Name "message" -Value $green -Scope 1
  New-Variable -Name "normal" -Value $white -Scope 1
  New-Variable -Name "warning" -Value $yellow -Scope 1
  New-Variable -Name "caution" -Value $cyan -Scope 1
  New-Variable -Name "notice" -Value $cyan -Scope 1
}

このようにしておけば、利用時はalias指定した名称でスプラット指定するだけです。 設定を読み込んで試します。

Get-WriteHostColourSplat
Write-Host "hoge" @caution

まとめ

閾値などの表示には、色別表示が便利ですね。