先分清两个 PowerShell

Windows 自带的 Windows PowerShell 5.1(powershell.exe)和 PowerShell 7(pwsh.exe)完全是两回事:7 基于 .NET、跨平台、性能更好且还在持续更新,5.1 已经停在 5.1.x 只修安全补丁。用 $PSVersionTable.PSVersion 看一眼版本,如果还在 5.1,就别再往里投入配置了。安装走 winget 最省事,Windows Terminal 一起装;装完在 Terminal 设置里把默认 profile 指向 PowerShell 而不是老的 5.1。

winget install --id Microsoft.PowerShell -e
winget install --id Microsoft.WindowsTerminal -e
pwsh -NoProfile -Command '$PSVersionTable.PSVersion.ToString()'

Terminal 的 settings.json

设置文件里 $schema 那行别删,能换来完整的键位和 profile 补全。profiles.defaults 放通用项,list 里逐个加 profile;GUID 用 PowerShell 里 [guid]::NewGuid() 生成,或直接让 source 自动发现。字体推荐装 Cascadia Code 连字版,中文等宽可以换更纱黑体 SC。

{
  "$schema": "https://aka.ms/terminal-profiles-schema",
  "defaultProfile": "{PowerShell 7 对应的 guid}",
  "initialCols": 120,
  "initialRows": 32,
  "profiles": {
    "defaults": {
      "font": { "face": "Cascadia Code", "size": 12 },
      "opacity": 92,
      "useAcrylic": true,
      "startingDirectory": "D:/wwwroot",
      "scrollbarState": "hidden"
    },
    "list": [
      { "name": "Git Bash", "commandline": "C:/Program Files/Git/bin/bash.exe", "icon": "C:/Program Files/Git/mingw64/share/git/git-for-windows.ico" },
      { "name": "Ubuntu", "source": "Windows.Terminal.Wsl" }
    ]
  },
  "keybindings": [
    { "keys": "ctrl+shift+t", "action": "newTab" },
    { "keys": "ctrl+shift+w", "action": "closeTab" }
  ]
}

$PROFILE 里真正有用的几行

用 notepad $PROFILE 打开(文件不存在就先 New-Item -Force 建)。oh-my-posh 管提示符,PSReadLine 开历史预测和列表视图,再补几个缩短日常敲键的别名。profile 是每次启动都执行的脚本,别往里塞耗时的网络请求或大循环,否则每个新标签页都卡一下。

winget install --id JanDeDobbeleer.OhMyPosh -e
notepad $PROFILE
oh-my-posh init pwsh --config "$env:POSH_THEMES_PATH/jandedobbeleer.omp.json" | Invoke-Expression
Set-PSReadLineOption -PredictionSource History
Set-PSReadLineOption -PredictionViewStyle ListView
Set-PSReadLineKeyHandler -Key UpArrow -Function HistorySearchBackward
Set-Alias -Name ll -Value Get-ChildItem
function gst { git status --short }

三个必踩的坑

  • 执行策略:新建 profile 后启动报"禁止运行脚本",用 Set-ExecutionPolicy -Scope CurrentUser RemoteSigned,只改当前用户,别去动 LocalMachine。
  • 中文乱码:在 profile 里设 [Console]::OutputEncoding = [System.Text.Encoding]::UTF8 和 $OutputEncoding 的编码,前者管屏幕输出,后者管管道给外部程序的字节;老脚本调用 chcp 65001 只是临时补丁。
  • profile 不止一份:管理员窗口、普通窗口、VS Code 内嵌终端、pwsh 与 powershell 各读各的路径,改了没生效先打印 $PROFILE 看实际落在哪。

顺带一提,Terminal 里加 Git Bash 和 WSL 的 profile 之后,用 Ctrl+Shift+数字 直接切到对应标签,比开三个窗口清爽;把 startingDirectory 设成项目根,新标签页不用每次 cd 半天。