我需要在数百台计算机上远程编辑一个名为 nsclient.ini 的文件,该文件包含一些命令定义。例如:
[/settings/external scripts/scripts]
check_event="C:\Program Files\NSClient++\scripts\Eventlog.exe" -e System -t Error
check_event_application="C:\Program Files\NSClient++\scripts\Eventlog.exe" -e Application -t Error
check_activedir=cscript "C:\Program Files\NSClient++\scripts\Check_AD.vbs" //nologo
我需要在 [/settings/external scripts/scripts] 下方添加一个新行,这个新行不应覆盖下面的现有行。
感谢您的帮助。
答案1
使用本机 PowerShell cmdlet:
# Set file name
$File = '.\nsclient.ini'
# Process lines of text from file and assign result to $NewContent variable
$NewContent = Get-Content -Path $File |
ForEach-Object {
# Output the existing line to pipeline in any case
$_
# If line matches regex
if($_ -match ('^' + [regex]::Escape('[/settings/external scripts/scripts]')))
{
# Add output additional line
'Your new line goes here'
}
}
# Write content of $NewContent varibale back to file
$NewContent | Out-File -FilePath $File -Encoding Default -Force
# Set file name
$File = '.\nsclient.ini'
# Process lines of text from file and assign result to $NewContent variable
$NewContent = [System.IO.File]::ReadAllLines($File) |
ForEach-Object {
# Output the existing line to pipeline in any case
$_
# If line matches regex
if($_ -match ('^' + [regex]::Escape('[/settings/external scripts/scripts]')))
{
# Add output additional line right after it
'Your new line goes here'
}
}
# Write content of $NewContent varibale back to file
[System.IO.File]::WriteAllLines($File, $NewContent)