LoginSignup
0
0

More than 1 year has passed since last update.

PowerShellのプロンプトの表示をカスタマイズする(短くしたり)

Last updated at Posted at 2022-09-10

TL;DR

フォルダー階層が深すぎるとき、PowerShellのプロンプトが長くなり過ぎて見にくい。この場合だけある程度短いパスで表示するように変更してみるよ。
変更の維持・反映にはユーザーのProfileを使用するよ。

似たような文脈のネタでPyCharmでteminalを(venv)pwshにするというのも書いているので、今はもう起こらないかもしれないけど、同じことでハマってる方はご参考まで。

何はともあれプロファイルスクリプトの場所

利用しているユーザーのプロファイルを設定するスクリプトの場所を調べる。bashでいうところの~/.bash_profile(いや、.bashrcか?まあいいか)。

$profileを参照して Microsoft.PowerShell_profile.ps1 があるパスを見つける1

PS> Write-Host $profile
# U:\path\to\Microsoft.PowerShell_profile.ps1

プロファイルを編集する

そしたら適当なエディタで開いて、中身を編集する。

PS> code $profile   # VSCodeで開く

ここにpromptという関数を作ると、それが反映される。
今回は、

  • 文字数が42を超えたら間を"…"で省略する
  • でも、今いるフォルダ名は全文で出す
  • そもそも今いるフォルダ名が長すぎる場合は"…\超長いフォルダ名"みたいに出す

をしてみる。ついでに、サンプルにあったやつで、管理者権限なら管理者権限とわかるようにするのをやってみる。

ちゃんとテストしてないのでおかしなところあったらご指摘くださいまし。

function prompt {
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = [Security.Principal.WindowsPrincipal] $identity
    $adminRole = [Security.Principal.WindowsBuiltInRole]::Administrator
    $ctx_txt = ''
    if (Test-Path variable:/PSDebugContext) { $ctx_txt = '(DBG)' }
    elseif ($principal.IsInRole($adminRole)) { $ctx_txt = '(ADM)' }
    else { $ctx_txt = '' }

    $location_path = ( Get-Location ).path
    $max_path_len = 42
    $location_path_to_show = ""

    if ($location_path.Length -gt $max_path_len) {
        $leaf = ( Split-Path $location_path -Leaf )
        
        if ( $leaf.Length -gt $max_path_len ) {
            $location_path_to_show = "…\" + $leaf
        }
        else {
            [int]$b = $max_path_len - $leaf.Length
            $location_path_to_show = $location_path.Substring(0, $b) + "…\" + $leaf
        }
    }
    else {
        $location_path_to_show = (Get-Location).Path
    }

    'PS' + $ctx_txt + ' ' + $location_path_to_show +
    $(if ($NestedPromptLevel -ge 1) { '>>' }) + '> '
}

結果

できた。

PS Microsoft.PowerShell.Core\Fi\@2022_work>

Links

  1. $profileはVSCodeで参照するとMicrosoft.VSCode_profile.ps1 (VSCodeのprofile)を返すようなので、VSCodeのPowerShell Extentionでプロファイルを探す場合には一回powershell(またはps coreを使ってるならpwsh)を叩いてからWrite-Host $profile叩くとよい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0