Search code examples
powershellpowershell-3.0

How to update and add a block of text a conf.d file using Powershell?


I have a config file named "conf.d" that I need to update with powershell automation. Here is what 1 block of the conf.d file looks like:

- name: NameHere

    url: www.example.com

    http_response_status_code: (1|2|3)\d\d

    collect_response_time: true

    disable_ssl_validation: false

    ignore_ssl_warning: true

    check_certificate_expiration: true

    days_warning: 30

    days_critical: 10

    tags:
        - Name:Tag

The rest of the file is just that block of configuration repeated over and over on top of each other. Is there a Powershell script that I can write that will add another one of these blocks to the end of the file?

Ideally I would do this with variables as well in the name, url, and tags slots.


Solution

  • Yes, you can. In order to do so you might want to prepare a block as a template and include variables that can be replaced by their values. As mentioned in the comments you can use Add-Content to append on the file or you could use Out-File with -append.

    $name = "test"
    $content = "Name:$name"
    $content | Out-File test.txt