用 PowerShell 批量替换多个文件中的文本

三个 cmdlet 组成的管道即可替换目录树下所有文件中的字符串——Windows 版的 sed -i。

Windows文件PowerShell查找替换中风险
用 Get-ChildItem -Recurse 管道接 ForEach-Object,对 Get-Content -Raw 的结果执行 -replace,再用 Set-Content 写回。

01命令

命令
$ Get-ChildItem 'C:\Proj' -Filter *.txt -Recurse | ForEach-Object { (Get-Content $_.FullName -Raw) -replace 'old-domain.com','new-domain.com' | Set-Content $_.FullName }

02作用说明

-replace 使用正则表达式,. 和 ( 等字符需要转义;普通 -replace 不区分大小写,需要区分时用 -creplace。用 -Raw 读入再写回可保持换行符一致。这一模式常用于一次性更新整个仓库中的配置文件、连接字符串或版权头。

03风险

风险中风险
使用条件PowerShell
!注意: 没有撤销机制——先在副本上验证正则,或在循环覆盖前先执行 Copy-Item $_.FullName "$($_.FullName).bak" 备份。

04撤销

✓无需撤销——该命令不会改变持久状态。

05来源

  • about_Regular_Expressions | Microsoft Learn
    Microsoft · vendor-doc · 2026-09-17
    依据: Microsoft documents the -replace operator, which performs regex-based replacement and is case-insensitive in PowerShell by default.
  • The PowerShell Replace Operator
    SS64 · technical · 2026-09-17
    依据: SS64 demonstrates find-and-replace across files using Get-ChildItem, Get-Content, -replace and Set-Content.

最后验证: 2026-09-17 · 分类: 文件与文件夹

06相关方案