更改 PowerShell 命令提示符样式的代码

张开发
2026/4/8 8:51:44 15 分钟阅读

分享文章

更改 PowerShell 命令提示符样式的代码
主要就是修改$PROFILE文件自定义 prompt 函数如下functionprompt{# ---------- 配置颜色 ----------$branchColorCyan$dirtyColorRed$dateTimeColorDarkGray$pathColorWhite# ---------- 左侧路径 ----------$pathText$executionContext.SessionState.Path.CurrentLocation.Path# ---------- Git 分支 dirty ----------$branch$null$isDirty$falseif(Get-Commandgit-ErrorAction SilentlyContinue){try{$branch git branch--show-current2$nullif($branch){$status git status--porcelain 2$nullif($status){$isDirty$true}}}catch{}}# ---------- 右侧时间 ----------$dtGet-Date-Formatyyyy-MM-dd HH:mm:ss$width$Host.UI.RawUI.WindowSize.Widthif(-not$width){$width 120}# ---------- 输出左侧 ----------Write-Host$pathText-NoNewline-ForegroundColor$pathColorif($branch){Write-Host [$branch-NoNewline-ForegroundColor$branchColorif($isDirty){Write-Host*-NoNewline-ForegroundColor$dirtyColor}Write-Host]-NoNewline-ForegroundColor$branchColor}# ---------- 右对齐时间 ----------$dtLen$dt.Length$targetCol[Math]::Max(0,$width-$dtLen-1)try{$pos$Host.UI.RawUI.CursorPosition$pos.X $targetCol$Host.UI.RawUI.CursorPosition $pos}catch{$leftLen($pathText(if($branch){ [$branch(if($isDirty){*}else{})]}else{})).Length$spaces[Math]::Max(1,$targetCol-$leftLen)Write-Host( *$spaces)-NoNewline}Write-Host$dt-NoNewline-ForegroundColor$dateTimeColornPS }步骤打开$PROFILEnotepad $PROFILE修改$PROFILE添加上述函数运行. $PROFILE手动加载或重新打开 PowerShell 让它生效上述代码的效果如下

更多文章