3.2 KiB
3.2 KiB
Windows / PowerShell 环境
- 功能:约束本机 shell 的用法,避免把 Bash 语法交给 PowerShell、避免 Windows 兼容与编码坑。
- 何时用:执行 shell 命令时;命令报
ParserError/CommandNotFoundException/ParameterBindingException/Cannot find path/ PythonSyntaxError时;要写脚本、处理引号或中文编码时;操作 Windows 原生组件时;同一命令连续失败两次后。
规则
- 默认 shell 视为 Windows PowerShell 5.1;不要假设 Bash、zsh 或 PowerShell 7。必要时先查
$PSVersionTable.PSVersion、Get-Command pwsh -ErrorAction SilentlyContinue。 - Windows 桌面、Visual Studio/MSBuild、WPF/WinForms/WinUI、COM、注册表、服务、系统托盘、PyInstaller、UI 自动化等任务优先用 Windows 原生环境;不要默认切 WSL。
- 仅在 Linux 部署、Bash 脚本、Linux 工具链或项目本身位于 WSL 时考虑 WSL;跨环境前确认仓库路径、依赖和运行目标。
- 禁止把 Bash 语法交给 PowerShell:
python - <<'PY'、cat <<EOF、export、source、rm -rf、cp -r、xargs、Bash 后台&。 - PowerShell 中
&是调用运算符;URL 或参数含&时整体单引号引用。 - 避免 PowerShell 5.1 下使用 Bash 风格
&&/||;顺序步骤用多行 PowerShell、短命令或多次工具调用。 - 参数含空格、括号、中文、
&|;><$或引号时默认用单引号;只有需要变量插值时才用双引号。 - 外部程序路径可能有空格时,用
& 'C:\path with spaces\tool.exe' arg1;多参数外部命令优先数组 splatting。 - PowerShell 数组传给外部程序时直接 splat;不要把多个路径或参数拼成一个带空格的字符串。
- 文件操作优先 PowerShell 原生命令和
-LiteralPath;遇到参数不存在先按 PowerShell 5.1 兼容写法处理。 - 复杂 Python 不用
python -c;涉及 SQL、JSON、中文、反斜杠路径、换行或多层引号时,用仓库脚本、临时.py或apply_patch。 - 禁止在 PowerShell 用 Bash here-doc。临时传 Python 源码只允许 PowerShell here-string,且尽量保持 ASCII。
- Python 源码含中文常量时,不通过 PowerShell 管道传给
python -;用 UTF-8 脚本文件、仓库脚本或\uXXXX。 - 不只依赖
chcp 65001解决编码;必要时同时设置$OutputEncoding、[Console]::InputEncoding、[Console]::OutputEncoding、PYTHONUTF8、PYTHONIOENCODING。 - 搜索文本/文件优先
rg/rg --files;多个根目录作为多个独立参数传入。 sqlite3.exe不存在时用 Pythonsqlite3查询,不反复尝试不存在的 CLI。- 编辑文件优先
apply_patch;不要用复杂 PowerShell 字符串重写文件。 - 数据库或生产内容写操作前先查询当前数据;写入必须有明确筛选条件,禁止无条件
DELETE/UPDATE。 - 出现
ParserError、CommandNotFoundException、ParameterBindingException、Cannot find path、PythonSyntaxError时,先排查 shell 语法、引用、PATH、PowerShell 5.1 兼容和workdir。 - 同一 PowerShell 命令连续失败两次后,停止微调长命令;改短命令、脚本文件、数组 splatting 或分步验证。