替换文件中的某个内容

 脚本一:

 1 #定义查找替换函数,用于修改配置文件中的IP(定义要查找的包含某个关键字的行,该关键字不是要替换的内容,比如此处要替换的是行 Hostname=10.4.20.20 中等号后面的内容)
 2 Function SearchReplace ($keyword,$newword,$filepath)
 3    {
 4     $confs = gc $filepath
 5     $linekeyword = (Select-String -Path $filepath  -Pattern $keyword -List).Line
 6     #定义要被替换的内容
 7     $replaceword = $linekeyword.Split("=")[1]
 8 
 9     Clear-Content $filepath
10     foreach ($line in $confs)
11         {
12          $lineold = $line.Split("=")[1]
13          $linenew = $line.Replace($replaceword,$newword)
14          Add-Content $filepath -Value $linenew
15         }
16    }
17 #定义所查找行中的关键字
18 $keyword = "Hostname"
19 #定义要替换后的内容
20 #$ip = (gwmi win32_networkadapterconfiguration -filter "ipenabled = 'true'").ipaddress[0]
20 $ip = ((gwmi win32_networkadapterconfiguration | ? {$_.DefaultIPGateway -ne $null}).IPAddress)[0]
21 #定义所查找替换的文件路径 22 $filepath = "C:zabbix_agentconfzabbix_agentd.win.conf" 23 24 SearchReplace $keyword $ip $filepath

脚本二:

 1 #该脚本先对包含关键字的行内容进行替换,然后再对整个文件进行遍历,将 整行 作为关键字进行替换
 2 Param($keyword,$newword)
 3 
 4 $File = "Update_Config_ERP.txt"
 5 $Currentpath = Split-Path -parent $MyInvocation.MyCommand.Definition 
 6 $Filepath = Join-Path $Currentpath $File
 7 
 8 Function SearchReplace ($keyword,$newword)
 9 {
10 $confs = gc $Filepath
11 If (Select-String -Path $Filepath -Pattern $keyword -Encoding default -Quiet)
12 {
13 $linekeyword = (Select-String -Path $Filepath -Pattern $keyword -Encoding default -List).Line  #只查找包含关键字的第一行
14 $replaceword = $linekeyword.Split("=")[1]
15 $linenewword = $linekeyword.Replace($replaceword,$newword)
16 
17 Clear-Content $Filepath
18 Foreach ($line in $confs)
19 {
20 $linenew = $line.Replace($linekeyword,$linenewword)
21 Add-Content $Filepath -Value $linenew
22 }
23 }
24 }
25 SearchReplace 其他出版物流1 0

#或者也可以先遍历每行,然后对每行是否包含某个关键字进行判断、替换

三、查找替换关键字

 1 $filepath = "d:ADServer_List.txt"
 2 $keyword="nn"
 3 $newword = "aab"
 4 function SearchReplace ($filepath,$keyword,$newword)
 5 {
 6  $FileContent = gc $filepath
 7  Clear-Content $filepath -Force
 8  foreach ($line in $FileContent)
 9     {
10      $line.replace($keyword,$newword) |out-file $filepath -append
11     }
12 }
13 
14 
15 SearchReplace $filepath $keyword $newword

四、通过静态类替换内容:

将E: mpzabbix_agentd.win.conf中的10.10.2.2替换为zabbix.x.com

$content = [System.IO.File]::ReadAllText("E:	mpzabbix_agentd.win.conf").Replace("10.10.2.2","zabbix.x.com")
[System.IO.File]::WriteAllText("E:	mpzabbix_agentd.win.conf", $content)
(Get-Content E:	mpzabbix_agentd.win.conf).replace("10.16.2.2","zabbix.x.com") | Set-Content E:	mpzabbix_agentd.win.conf

注意周围的括号(Get-Content file.txt):
如果没有括号,内容将一次读取一行,然后沿着管道向下流动,直到它到达文件外或设置内容为止,后者试图写入同一个文件,但它已经被get-content打开,您将得到一个错误。括号使内容读取操作只执行一次(打开、读取和关闭)。只有当所有行都已被读取时,它们才会一次被管道化一次,当它们到达管道中的最后一个命令时,它们才能被写入文件

原文地址:https://www.cnblogs.com/dreamer-fish/p/3880339.html