「$host.ui.rawui」に関する考察

概要

ホストの低レベル情報の操作インターフェース。

  • Window情報の操作(タイトル、サイズ、位置、前景色、背景色、カーソル)
  • スクリーンバッファの操作

型:System.Management.Automation.Internal.Host.InternalHostRawUserInterface

確認方法
PS C:\> $host.ui.rawui.GetType().FullName
System.Management.Automation.Internal.Host.InternalHostRawUserInterface

主要メソッド

  • ReadKey
  • ScrollBufferContents
  • SetBufferContents

主要プロパティ

  • ForegroundColor
  • BackgroundColor
  • BufferSize
  • CursorPosition
  • CursorSize
  • MaxPhysicalWindowSize
  • MaxWindowSize
  • WindowPosition
  • WindowSize
  • WindowTitle

継承/実装元の型:System.Management.Automation.Host.PSHostRawUserInterface

確認方法
PS C:\> $host.ui.rawui.GetType().BaseType.FullName
System.Management.Automation.Host.PSHostRawUserInterface

継承階層

確認方法
PS C:\> $host.ui.rawui.PSObject.TypeNames
System.Management.Automation.Internal.Host.InternalHostRawUserInterface
System.Management.Automation.Host.PSHostRawUserInterface
System.Object

サンプル:指定した矩形領域を特定文字で描画する

function Draw-Rectangle
    ([int]$left, [int]$top, [int]$right, [int]$bottom, [String]$char)
{
    #BufferCell生成
    $cell = New-Object System.Management.Automation.Host.BufferCell
    $cell.Character = $char
    $cell.ForegroundColor = $host.ui.rawui.ForegroundColor
    $cell.BackgroundColor = $host.ui.rawui.BackgroundColor

    #Rectangle生成
    $rect = New-Object System.Management.Automation.Host.Rectangle
    $rect.Left = $left
    $rect.Top = $top
    $rect.Right = $right
    $rect.Bottom = $bottom

    #Bufferで塗りつぶす
    $Host.UI.RawUI.SetBufferContents($rect, $cell)
}
実行例1
#スクリーンをクリア(全領域をスペースで埋める)
Draw-Rectangle -1 -1 -1 -1 " "
実行例2
#スクリーンの左上に10x10の「X」を描画
Draw-Rectangle 0 0 10 10 "X"

サンプル:カーソル位置の変更

function Move-Cursor([int]$x, [int]$y)
{
    $coordinate = New-Object System.Management.Automation.Host.Coordinates($x,$y)
    $Host.UI.RawUI.CursorPosition = $coordinate
}
実行例1
#カーソルを左上に移動
Move-Cursor 0 0
実行例2
#カーソルを(10,5)に移動
Move-Cursor 10 5

補足

内部関数である「Clear-Host」は、スクリーンをクリアしてカーソルを最上行に移動しますが「Clear-Host」の内部処理は以下と同じです。

function Clear-Host
{
    Draw-Rectangle -1 -1 -1 -1 " "
    Move-Cursor 0 0
}

上記を定義すると「Clear-Host」or「cls」でスクリーンのクリア&カーソル最上行移動ができます。