Add Line to Text File After Specific Line with Powershell
I Have to Edit Remotely a File Called Nsclient. Ini on Hundreds of Computers, the File Contains Some Command Definitions. for Example: [/Settings/External...
I have to edit remotely a file called nsclient.ini on hundreds of computers, the file contains some command definitions. For example:
[/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
I need to add a new line just beneath [/settings/external scripts/scripts] This new line should not overwrite the existing lines beneath.
Thanks for your help.
1 Answer
Using native PowerShell cmdlets:
# 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
Using .Net static methods (ReadAllLines\WriteAllLines):
# 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)