Adiciona linha ao arquivo de texto após uma linha específica com o PowerShell

1

Eu tenho que editar remotamente um arquivo chamado nsclient.ini em centenas de computadores, o arquivo contém algumas definições de comando. Por exemplo:

[/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

Eu preciso adicionar uma nova linha logo abaixo de [/ settings / scripts externos / scripts] Esta nova linha não deve sobrescrever as linhas existentes abaixo.

Obrigado pela sua ajuda.

    
por ThomasC. 05.10.2014 / 15:28

1 resposta

1

Usando cmdlets nativos do PowerShell:

# 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 {
        # If line matches regex
        if($_ -match ('^' + [regex]::Escape('[/settings/external scripts/scripts]')))
        {
            # Output this line to pipeline
            $_

            # And output additional line right after it
            'Your new line goes here'
        }
        else # If line doesn't matches regex
        {
            # Output this line to pipeline
            $_
        }
    }

# Write content of $NewContent varibale back to file
$NewContent | Out-File -FilePath $File -Encoding Default -Force

Usando métodos estáticos .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 {
        # If line matches regex
        if($_ -match ('^' + [regex]::Escape('[/settings/external scripts/scripts]')))
        {
            # Output this line to pipeline
            $_

            # And output additional line right after it
            'Your new line goes here'
        }
        else # If line doesn't matches regex
        {
            # Output this line to pipeline
            $_
        }
    }

# Write content of $NewContent varibale back to file
[System.IO.File]::WriteAllLines($File, $NewContent)
    
por 26.03.2015 / 11:43