我的公司已部署Splunk来收集日志并报告系统更改。 Splunk使用两个文件-input.conf和server.conf来跟踪现有主机名并将其报告给Splunk控件。
如果主机名更改(在我们的环境中很常见),系统将报告“主机健全性检查损坏”,要求我们登录每个系统并用新主机名替换旧主机名。
这很难在现场使用1000个系统。
我想使这一过程自动化,并且我编写的脚本有问题(见下文)。
输入和服务器都对.conf文件使用这种格式(.conf只是扩展名为.conf的txt文件)。
Host = systemname
下面的脚本当前将读取文本文件,然后代替替换“ systemname”,它将更改附加到现有值的末尾。即。而不是hostname1
代替hostname2
⇔Hostname2Hostname1
。
$InputsOLD = "host = *"
$InputsNEW = "host = $Env:COMPUTERNAME"
Get-Content "C:\Program Files\SplunkUniversalForwarder\etc\system\local\inputs.conf" |
Foreach-Object {$_ -replace "$InputsOLD","$InputsNEW"} |
Set-Content "C:\Program Files\SplunkUniversalForwarder\etc\system\local\inputs_1.conf"
$ServerOLD = "serverName = *"
$ServerNew = "serverName = $Env:COMPUTERNAME"
Get-Content "C:\Program Files\SplunkUniversalForwarder\etc\system\local\server.conf" |
Foreach-Object {$_ -replace "$ServerOLD","$ServerNew"} |
Set-Content "C:\Program Files\SplunkUniversalForwarder\etc\system\local\server_1.conf"
答案 0 :(得分:3)
The -replace
operator matches based on a regular expression. So your match expression:
"host = *"
will end its match after it matches its first "host = " not including the host name, and that's what gets replaced, leaving everything intact afterwards. To include the host name in the match expression, use this regular expression:
"host = .*"
答案 1 :(得分:0)
I'd use a regular expression which uses a zero length assertion
to match anything on the line following the keyword (even a literal asterisk)
This script changes inplace, using the same file name on save.
## Q:\Test\2019\01\18\SO_54259368.ps1
Push-Location "C:\Program Files\SplunkUniversalForwarder\etc\system\local"
$Clie = "inputs.conf"
$Serv = "server.conf"
(Get-Content $Clie) -replace "(?<=^host = ).*$",$Env:COMPUTERNAME | Set-Content $Clie
(Get-Content $Serv) -replace "(?<=^serverName = ).*$",$Env:COMPUTERNAME | Set-Content $Serv
Pop-Location