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 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.

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)
1
Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest