10
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PowerShellのプロンプトをBash風にする。

Last updated at Posted at 2018-06-24

概要

PowerShellでは、プロンプトのカスタマイズができるということを知ったので、興味本位でBash風にしてみました。

確認環境

Name Value
PSVersion 6.0.2
PSEdition Core
GitCommitId v6.0.2
OS Microsoft Windows 10.0.17134
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0

前準備

profileは、最初は存在しないので、作成しておきます。

 new-item -type file -Force $profile

方法

promptメソッドを定義して、戻り値にプロンプトに表示させたい文字列を指定する。

Microsoft.PowerShell_profile.ps1
function prompt () {  
    "[$($env:USERNAME)@$($env:COMPUTERNAME) " + (Split-Path (Get-Location) -Leaf) + "] > " 
}
# ついでに、初期位置を変更しておく。
Set-Location "C:\Users\{UserName}\Documents\GitHub"

変更を保存して、PowerShellを再起動すると、こんな風に変わります。(ユーザー名はマスクしてるけど。)
image.png
Visual Studio Code用コンソールだと、ファイル名がMicrosoft.VSCode_profile.ps1に代わるようです。
image.png

おまけ

メソッドの戻り値が表示内容になるので、管理者で起動したときに、表示を変更させて、さらにBash風に(ry
(もう、Linux使えよ。)
image.png

Microsoft.PowerShell_profile.ps1


function prompt () {
    $prompt = if (-not(([Security.Principal.WindowsPrincipal] `
                    [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
                    [Security.Principal.WindowsBuiltInRole] "Administrator"`
            ))) {
        " > "
    }else{
        " # " 
    }
    "[$($env:USERNAME)@$($env:COMPUTERNAME) " + (Split-Path (Get-Location) -Leaf) + "]${prompt}" 
}
Set-Location "C:\Users\{UserName}\Documents\GitHub"

参考資料

10
6
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
10
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?