如何使用 Powershell 更新和添加文本块 conf.d 文件?

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

我有一个名为 "conf.d" 的配置文件,我需要使用 Powershell 自动化对其进行更新。这是 conf.d 文件的 1 个块的样子:

- 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

文件的其余部分只是不断重复的配置块。是否有我可以编写的 Powershell 脚本将这些块中的另一个添加到文件末尾?

理想情况下,我会在名称 url 和标签插槽中使用变量。

是的,你可以。为此,您可能需要准备一个块作为模板,并包含可由其值替换的变量。如评论中所述,您可以将 Add-Content to append on the file or you could use Out-File-append.

一起使用
$name = "test"
$content = "Name:$name"
$content | Out-File test.txt