3

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"

2 Answers 2

4

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

You could use -notmatch and skip needing an else and the superfluous return. And you should escape your spaces in the regex.
I think you updated \s into the replacement string accidentally too. Should still be a space.
@BenH Find&Replace strikes again
1

An alternative that's able to cope with the action key being located anywhere in the [MyAction_Log] section

$Inside = $False
$Modified = $False
$Path = "$( $env:ProgramFiles )\prog\file.conf"

$NewLines = Get-Content $Path | 
    ForEach-Object {

        if( $_.Trim() -like "[*]" ) { $Inside = $False }
        if( $_.Trim() -like "*[MyAction_Log]*" ) { $Inside = $True }

        If( $Inside -and $_ -like "action = *" -and $_ -notlike "*run fast*" ) { $Modified = $True; "action = run fast" } else { $_ }
    }

If( $Modified ) { $NewLines | Set-Content $Path }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.