iT邦幫忙

2024 iThome 鐵人賽

DAY 12
0
佛心分享-我的私藏工具箱

正則!好好表達系列 第 12

PowerShell的replace Regex

  • 分享至 

  • xImage
  •  

在上個鐵人賽題目:作業系統的專武。倒數第二篇:PowerShell雙帳密過版。
https://ithelp.ithome.com.tw/articles/10349948
其實還少了一段是留給這次題目使用。
開發Tableau報表所產出的twb檔是XML格式,內容有包括要連接Server的IP、port、服務名稱等,而PG一定是在開發環境測試OK後才過版,因此這些twb檔裡的開發環境的資訊,都要改成UAT及PROD的資訊。
在PowerShell裡使用Regex可參考:
https://learn.microsoft.com/zh-tw/powershell/module/microsoft.powershell.core/about/about_regular_expressions?view=powershell-7.4
以下是我實質替換twb裡所有內容部份程式碼:

$folder = "D:\UAT\TABLEAU\*.twb"
$port = 1234
$service = "RPT"
Get-ChildItem $folder -Recurse | ForEach { (Get-Content -Encoding UTF8 $_ | ForEach {$_ -replace '10.1.2.3', '$ip'}) | Set-Content -Encoding UTF8 $_ }

Get-ChildItem $folder -Recurse | ForEach { (Get-Content -Encoding UTF8 $_ | ForEach {$_ -replace "port='.+?'", "port='$port'"}) | Set-Content -Encoding UTF8 $_ }

Get-ChildItem $folder -Recurse | ForEach { (Get-Content -Encoding UTF8 $_ | ForEach {$_ -replace "service='.+?'", "service='$service'"}) | Set-Content -Encoding UTF8 $_ }

利用Get-ChildItem遞迴取得$folder裡所有twb檔,讀出時用UTF-8編碼,使用-replace參數置換。其中.+?這個Pattern和Day 2那篇用Regex取XML值方法一樣。差別是這裡是展示用PowerShell的使用方式。


上一篇
匯出相依jar的清單
下一篇
遮蔽敏感性資訊的Perl
系列文
正則!好好表達14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言