天天看點

替換檔案中的某個内容

 腳本一:

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_agent\conf\zabbix_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:\tmp\zabbix_agentd.win.conf中的10.10.2.2替換為zabbix.x.com

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