[转]Powershell中替换文件内容的方法

经某度搜索,好像全世界的方法是:

Get-Content $zabbix_agent | Foreach-Object {$_ -replace "ServerActive=127\.0\.0\.1","ServerActive=100\.100\.100\.100"} | Out-File $zabbix_agent -Verbos -Force

  

如果你用了就大错特错了,这条命令永远会报错:

Set-Content : 文件“”正由另一进程使用,因此该进程无法访问此文件。

正确并实际使用的方法是:

Function sed($Filename, $Oldvalue, $Newvalue)
{
if (Test-Path $Filename) {
$content = get-content $Filename
clear-content $Filename
foreach($line in $content) {
$liner=$line.Replace($Oldvalue, $Newvalue)
Add-content $Filename -Value $liner
}
}
}

sed "c:\zabbix.conf" "Server=127.0.0.1" "Server=100.100.100.100"

————————————————
原文链接:https://blog.csdn.net/d9394952/article/details/118329737

posted @ 2022-03-22 10:43  Monbro  阅读(524)  评论(0编辑  收藏  举报