Author Posts

November 2, 2017 at 2:31 pm

Coming from the Linux world I would use sed for this but trying to use PowerShell to modify a config file. The file is located in C:\Program Files\NSClient++\nsclient.ini and inside that file there is a line that shows allowed hosts = . I need to add some additional IP addresses and some of these configs have 2 addresses and others have 3. So to make this easy I just wanted to comment out this original line of allowed hosts = to #allowed hosts = and then below it add a new line with allowed hosts = . Then restart my service with Restart-Service nscd so this new config file takes effect.

I think I am making this way harder than it has to be but I was able to figure out how to comment out my line with this
(get-content C:\Program Files\NSClient++\nsclient.ini) | foreach-object {$_ -replace "allowed hosts", "#allowed hosts"} | set-content C:\Program Files\NSClient++\nsclient.ini but I tried a few other examples and can't get a new line under it with the text I want.

Looking for some assistance. Thanks!

November 2, 2017 at 2:36 pm

PowerShell isn't the text manipulation machine that you're used to ;). And by building this as a “one-liner,” you're making it a bit harder on yourself.

Consider:

Get-Content whatever.ini |
ForEach-Object {
 If ($_ -like “allowed hosts”) { Write “#allowed hosts” }
 If ($_ -like “something else”) { Write “whatever” }
} | Set-Content whatever.ini

In other words, set up a series of test conditions for things you care about, and then use Write-Output (Write) to output whatever you'd like instead.

Does that help at all?

November 2, 2017 at 3:13 pm

Yes, thanks Don. I'll take your recommendation and try to put something together based on this example.

Text manipulating is much simpler with Linux that is true! 🙂

November 2, 2017 at 3:55 pm

Also maybe something like this:

$Content = Get-Content -Path SomeFile.ini

$NewContent = ForEach ($Line in $Content) {
    if ($Line -like "allowed hosts*")
    {
        Write-Output $("#" + $Line)
        Write-Output "allowed hosts = new IPs"
    }
    else
    {
        Write-Output $Line
    }
}
Set-Content -Path SomeFile.ini -Value $NewContent