Modify line and add new line after

Welcome Forums General PowerShell Q&A Modify line and add new line after

This topic contains 3 replies, has 3 voices, and was last updated by

 
Participant
1 year ago.

  • Author
    Posts
  • #83489

    Participant
    Points: 0
    Rank: Member

    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!

  • #83492

    Keymaster
    Points: 1,625
    Helping HandTeam Member
    Rank: Community Hero

    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?

  • #83495

    Participant
    Points: 0
    Rank: Member

    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! 🙂

  • #83504

    Participant
    Points: 22
    Rank: Member

    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
    

The topic ‘Modify line and add new line after’ is closed to new replies.