使用 PowerShell 在特定行之后添加行到文本文件

Tho*_*sC. 4 powershell command-line

我必须在数百台计算机上远程编辑一个名为 nsclient.ini 的文件,该文件包含一些命令定义。例如:

[/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
Run Code Online (Sandbox Code Playgroud)

我需要在 [/settings/external scripts/scripts] 下面添加一个新行,这个新行不应覆盖下面的现有行。

谢谢你的帮助。

bea*_*ker 7

使用本机 PowerShell cmdlet:

# 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
Run Code Online (Sandbox Code Playgroud)

使用.NET静态方法(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)
Run Code Online (Sandbox Code Playgroud)