コマンドで色の変更

PowerShellのコンソールに表示する文字列に対して、文字色や背景色を変更する方法は、Write-Host コマンドレットを使用して簡単に実現できます。

以下に、文字色と背景色を変更するサンプルコードを示します。

# 文字色を赤、背景色を黄色に設定してメッセージを表示
Write-Host "これは赤い文字で黄色の背景です。" -ForegroundColor Red -BackgroundColor Yellow

# 文字色を青、背景色を白に設定してメッセージを表示
Write-Host "これは青い文字で白の背景です。" -ForegroundColor Blue -BackgroundColor White

# 文字色を緑、背景色を黒に設定してメッセージを表示
Write-Host "これは緑の文字で黒の背景です。" -ForegroundColor Green -BackgroundColor Black

# "PowerShell"という文字列を青にし、その他は白で表示する
Write-Host "This is " -NoNewline
Write-Host "PowerShell" -ForegroundColor Blue -NoNewline
Write-Host " example." -ForegroundColor White

説明

オブジェクトの色で設定する方法

PowerShellコンソールに文字列を表示する際、文字色、背景色、フォント、大きさなどを変更するサンプルコードを以下に示します。PowerShell自体のコンソールではフォントとサイズの変更ができないため、これらは主に背景色と文字色に焦点を当てています。詳細なスタイリングが必要な場合は、WPFを使用してGUIを作成することをお勧めしますが、今回はコンソールでのスタイル変更に集中します。

PowerShellコンソールで文字列の色と背景色を変更する例

# 文字色と背景色を設定する
$foregroundColor = "Yellow"
$backgroundColor = "Blue"

# 背景色を変更
$Host.UI.RawUI.BackgroundColor = $backgroundColor
$Host.UI.RawUI.FlushInputBuffer()

# 文字色を変更
$Host.UI.RawUI.ForegroundColor = $foregroundColor

# メッセージを表示
Write-Host "この文字列は背景が青、文字色が黄色で表示されます。"

# 色をリセット
$Host.UI.RawUI.BackgroundColor = "Black"
$Host.UI.RawUI.ForegroundColor = "White"
$Host.UI.RawUI.FlushInputBuffer()

WPFを使用して詳細なスタイリングを行う例

WPFを使用する場合は、以下のようにXAMLで詳細なスタイリングを設定することができます。これにより、フォントサイズやスタイルもカスタマイズ可能です。

XAMLファイル(CustomWindow.xaml

<Window
    xmlns="<http://schemas.microsoft.com/winfx/2006/xaml/presentation>"
    xmlns:x="<http://schemas.microsoft.com/winfx/2006/xaml>"
    Title="Custom Styled Window" Height="200" Width="400">
    <Grid>
        <TextBlock Name="StyledText" Text="この文字列はカスタムスタイルで表示されます。"
                   FontSize="24"
                   FontWeight="Bold"
                   Foreground="White"
                   Background="Black"
                   TextAlignment="Center"
                   VerticalAlignment="Center"/>
    </Grid>
</Window>

PowerShellスクリプト(App.ps1

# 必要なアセンブリを読み込む
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName PresentationFramework

# XAMLファイルを読み込む
[xml]$Xaml = Get-Content "$PSScriptRoot\\\\CustomWindow.xaml"

# ウィンドウを作成
$reader = (New-Object System.Xml.XmlNodeReader $Xaml)
$window = [Windows.Markup.XamlReader]::Load($reader)

# ウィンドウを表示
$window.ShowDialog()

使用手順

  1. 上記のXAMLファイル (CustomWindow.xaml) と PowerShellスクリプト (App.ps1) を適切なディレクトリに保存します。