無印の PowerShell の場合は $host.UI.RawUI.WindowTitle
だけで指定できますが、コンソールエミュレータの Cmder ではもうひと工夫が必要でした。
最終的に下のような見た目になっています。
コード
結論から言うと、以前の記事 でも紹介した C# の SendMessage を使います。
ウィンドウハンドルの取得
(上の記事で紹介したものと同一です)
function Get-ConsoleWindowHandle {
$p = Get-Process -Id $PID
$i = 0
while ($p.MainWindowHandle -eq 0) {
if ($i++ -gt 10) {
return $null
}
$p = $p.Parent
}
return $p.MainWindowHandle
}
$Global:CONSOLE_HWND = Get-ConsoleWindowHandle
C# でクラス定義
if(-not ('PowerShell.Window' -as [type])) {
Add-Type -Name Window -Namespace PowerShell -MemberDefinition @'
[DllImport("user32.dll")]
private static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, string lParam);
public static void SetText(IntPtr hwnd, string text) {
SendMessage(hwnd, 0x000C, 0, text);
}
'@
}
function Set-ConsoleWindowTitle {
param (
$title
)
$hwnd = $Global:CONSOLE_HWND
if (-not $hwnd) {
return
}
[PowerShell.Window]::SetText($hwnd, $title)
}
プロンプトに組み込む
$PROFILE
内の prompt
関数内で呼び出すことで、作業しているディレクトリのフルパスを表示するようにします。
ついでにプロンプトの色を曜日別に変えています。在宅勤務が続いても曜日感覚を失わなくなる……かも?
function prompt {
$table = @(
<#日#> "DarkYellow",
<#月#> "Blue",
<#火#> "Magenta",
<#水#> "Cyan",
<#木#> "Green",
<#金#> "Yellow",
<#土#> "Gray"
)
$dailyColor = $table[[System.Convert]::toint32((Get-Date).DayOfWeek)]
$leaf = $pwd.Path | Split-Path -Leaf
Set-ConsoleWindowTitle -title $pwd.Path
if ($pwd.Path | Split-Path -Parent) {
Write-Host "~\" -BackgroundColor DarkGray -ForegroundColor White -NoNewline
}
Write-Host $leaf -BackgroundColor $dailyColor -ForegroundColor Black -NoNewline
return "`n> "
}