Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and Replace multi-line string

Tags:

powershell

I'm trying to find a string and add the string needed for a program.

I need the code to look to see if the action = run fast already exists and if so do nothing.

$Input = GetContent "${Env:ProgramFiles}\myprogram\file.conf"

$replace = @"
[MyAction_Log]
action = run fast 
"@

$Input -replace ('action = run fast') -replace ('\[MyAction_Log\]',$replace) | set-content "${Env:ProgramFiles}\myprogram\file.conf"
like image 368
A-Noob Avatar asked Mar 02 '26 16:03

A-Noob


1 Answers

I would check before wantonly replacing things you think exist. Also, never use $Input as a variable name; it's an automatic variable and won't do what you think it will (treat it as read-only).

$path = "$Env:ProgramFiles\prog\file.conf"
$file = Get-Content -Path $path
$replacementString = @'
[MyAction_Log]
action = run fast
'@

if ($file -notmatch 'action\s=\srun\sfast')
{
    $file -replace '\[MyAction_Log\]', $replacementString |
      Set-Content -Path $path
}
like image 65
Maximilian Burszley Avatar answered Mar 05 '26 10:03

Maximilian Burszley