4

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 1

7

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
  • 1
    You can simplify a bit the script by outputting $_ before the if and get rid of the else part. (I took the liberty to submit an edit, feel free to rollback if you wish to keep your more verbose code)
    – Pacopaco
    Dec 20, 2018 at 11:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .