Replace block text in ini file

Viewed 83

I need replace a block text inside a .ini file. My script is:

$oFile = "$Env:ProgramFiles (x86)\Advanced Monitoring Agent\Settings.ini
$oSettings = Get-Content -Path $oFile
$oPattern = '[PATCHMANAGEMENT](.*?)[SITECONCENTRATOR]'
$oTextToReplace = [regex]::match($oSettings , $oPattern).Groups[1].Value
$oNewFile = $oSettings -replace $oTextToReplace.ToString, "][" | out-file -FilePath $Env:ProgramFiles 
(x86)\Advanced Monitoring Agent\newSettings.ini

But it is not working. Can you help me with this? Sorry for my weak English. Greetings!

1 Answers

First of all, you should read the file in as a single variable:

$oSettings = Get-Content -Path $oFile -Raw

Next, use a DOTALL, or (?s) inline modifier at the pattern start, to make . match across lines. Also, escape [ that is outside a character class to make it match a literal [, else, it denotes a character class start. Then, enclose the tags you want to keep, not the text in between the tags:

$oPattern = '(?s)(\[PATCHMANAGEMENT]).*?(\[SITECONCENTRATOR])'

See the regex demo (just how it works).

The rest is a mere -replace:

$oNewFile = $oSettings -replace $oPattern, '$1$2' |
  out-file -FilePath "${Env:ProgramFiles(x86)}\Advanced Monitoring Agent\newSettings.ini"
Related