我有一個 test.properties 檔案,其格式如下:
hostName=hostName1
#hostName=hostName2
portNum=portNum1
#portNum=portNum2
我正在嘗試撰寫一個 powershell 腳本,該腳本在運行時會注釋任何主機名和埠號,并且只取消注釋我想要傳入的新的。
如果我有一個 $hostNameToUncomment 變數,那么我希望流程可以這樣說:
$hostNameToUncomment=hostName1
$propertiesFile = Get-Content ($path) | ForEach-Object {
if hostName anywhere is uncommented, comment it
if hostName value = $hostNameToUncomment,
Remove the '#' from that line
}
如何才能做到這一點?
uj5u.com熱心網友回復:
您可以使用 aswitch來讀取檔案并利用它的-Regex開關:
$toUncomment = 'hostname2'
$file = 'path/to/file.txt'
$result = switch -Regex -File($file)
{
"^#hostname=$toUncomment\b"
{
$Matches[0] -replace '^#'
}
"^[^#]\w =(?!$toUncomment).*"
{
$Matches[0] -replace '^','#'
}
Default
{
$_
}
}
$result | Out-File $file
請參閱https://regex101.com/r/sfhWz4/2以使用hostname2作為示例對兩個正則運算式的解釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/376428.html
標籤:电源外壳
