在Windows PowerShell中替换文件内容的命令需要分步骤处理,以下是实现方法:
powershell
# 查找并替换文件内容(⚠️操作前建议备份文件) Get-ChildItem -Recurse -File | ForEach-Object { # 读取文件内容(保持原编码) $content = Get-Content -LiteralPath $_.FullName -Encoding UTF8 -Raw # 执行替换(区分大小写) $newContent = $content -replace 'shitian', 'tiantian' # 如果内容有变化则写回文件 if ($newContent -ne $content) { Set-Content -LiteralPath $_.FullName -Value $newContent -Encoding UTF8 -NoNewline Write-Host "已修改文件: $($_.FullName)" } }
关键参数说明:
-Encoding UTF8:保持文件编码为UTF-8(根据实际文件编码调整)
-Raw:将文件作为单个字符串读取(保持换行符)
-NoNewline:禁止自动添加换行符(PowerShell 5.1+)
-replace:使用正则表达式替换(默认区分大小写)
--------------------------------------------------------------------------------------------------------------------------------
安全增强版(先预览再替换):
powershell# 步骤1:查找所有匹配的文件(预览)$targetFiles = Get-ChildItem -Recurse -File | Select-String -Pattern 'shitian' -List | Select-Object -ExpandProperty Path # 步骤2:逐个文件确认替换 $targetFiles | ForEach-Object { $file = $_ Write-Host "正在处理: $file" -ForegroundColor Cyan # 显示匹配内容 Get-Content $file | Select-String 'shitian' # 人工确认 $confirm = Read-Host "确认替换此文件?(y/n)" if ($confirm -eq 'y') { (Get-Content $file -Raw) -replace 'shitian','tiantian' | Set-Content $file -NoNewline Write-Host "已修改 ✅" -ForegroundColor Green } }
注意事项:
替换操作不可逆,建议先测试于副本文件
二进制文件(如exe/图片)会被跳过(因无法用Get-Content读取)
若需不区分大小写替换,可将-replace改为-ireplace
处理特殊字符时建议用LiteralPath而非Path