PowerShell 实战指南:执行策略、编码与跨平台脚本
为什么用 PowerShell 而非 cmd
PowerShell 是 Windows 上最强大的 shell,远超 cmd。它可以直接调用 .NET 类库、处理结构化数据(对象而非文本流)、支持管道和脚本模块。然而很多开发者仍然习惯写 cmd /c 包装命令——这是一个需要纠正的习惯。
执行策略(ExecutionPolicy)
Windows 默认禁止运行 .ps1 脚本(Restricted),这是安全考虑但也给开发者带来不便。
| 策略 | 含义 | 安全级别 |
|---|---|---|
| Restricted | 禁止所有脚本 | 最高(默认) |
| RemoteSigned | 本地脚本可运行,远程脚本需签名 | 中(推荐) |
| Bypass | 不做任何限制 | 低 |
| Unrestricted | 所有脚本可运行,远程脚本会提示 | 低 |
# 查看当前策略
Get-ExecutionPolicy
# 临时绕过(推荐:不改系统设置)
powershell -ExecutionPolicy Bypass -File ./script.ps1
# 永久设置当前用户(RemoteSigned 是开发者的合理选择)
Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
编码问题的根源与解决
这是 PowerShell 跨版本最头疼的问题——5.x 默认 GBK,7+ 默认 UTF-8。
PowerShell 5.x(Windows 自带)
# 默认编码:GBK(中文 Windows)
# 输出中文可能乱码
# 修复方案一:控制台编码
[Console]::OutputEncoding = [Text.Encoding]::UTF8
# 修复方案二:文件读写指定编码
Get-Content -Path file.txt -Encoding UTF8
Set-Content -Path file.txt -Value "中文" -Encoding UTF8
PowerShell 7+(推荐安装)
# 默认编码:UTF-8
# 基本不需要额外处理
# 安装:winget install Microsoft.PowerShell
跨版本最佳实践:所有脚本开头显式声明编码,避免隐式依赖。
# 脚本开头
$OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding =
New-Object System.Text.UTF8Encoding
常用模式与技巧
文件操作
# 递归搜索(比 dir /s 强大得多)
Get-ChildItem -Path . -Recurse -Filter "*.js" -Depth 3
# 按大小排序找大文件
Get-ChildItem -Recurse | Sort-Object Length -Descending | Select-Object -First 10
# 批量重命名
Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace 'old', 'new' }
进程管理
# 启动 GUI 程序(后台运行)
Start-Process "notepad.exe"
Start-Process "chrome.exe" -ArgumentList "--new-window https://example.com"
# 查找并结束进程
Get-Process node | Stop-Process
# 更安全:按名称匹配
Stop-Process -Name "node" -ErrorAction SilentlyContinue
JSON 处理
# 读取 JSON
$config = Get-Content config.json -Raw | ConvertFrom-Json
$config.name # 访问属性
# 修改并写出
$config.version = "2.0"
$config | ConvertTo-Json -Depth 10 | Set-Content config.json -Encoding UTF8
网络操作
# HTTP 请求(替代 curl)
$resp = Invoke-RestMethod -Uri "https://api.example.com/data" -Method GET
$resp.items | ForEach-Object { $_.name }
# 下载文件
Invoke-WebRequest -Uri "https://example.com/file.zip" -OutFile "file.zip"
PowerShell vs Git Bash:选型指南
| 场景 | 推荐 | 原因 |
|---|---|---|
| Git 操作 | Git Bash | 原生体验,SSH 支持好 |
| 文件系统操作 | PowerShell | 原生 Windows 路径支持 |
| 注册表 / WMI | PowerShell | Git Bash 做不到 |
| 结构化数据处理 | PowerShell | 对象管道 vs 文本管道 |
| 跨平台脚本 | PowerShell 7+ | Linux/macOS 也支持 |
| Unix 命令(grep/sed/awk) | Git Bash | 更自然 |
黄金法则
- 不要写
cmd /c包装命令——PowerShell 能直接做几乎一切 - 路径用反斜杠
C:\path,不要用正斜杠 - 优先用 PowerShell 7+(UTF-8 默认、跨平台)
- 操作敏感文件时用
-WhatIf预览,确认无误再执行