1

I want to run a powershell command only if a certain string does not exist in a certain file.

This is my script

$pattern='<!--add key="MaxNumCycles" value="40"/-->'
$textToAdd=$pattern + '

    <!--RerunMode: 1 write to DB, 2 write to DB and add to RUN export/-->
    <add key="RerunMode" value="0"/>'

$filename="C\temp\Software.exe.config"

[IO.File]::ReadAllText($filename).Replace($pattern,$textToAdd) | Set-Content $filename -Force

If the $textToAdd string is not in $filename then I want to run this script. How do I go about this?

1 Answer 1

1

That's simple enough, you just read the text in, pipe to Where, and perform the replace and Set-Content in a ForEach block.

$pattern='<!--add key="MaxNumCycles" value="40"/-->'
$textToAdd=$pattern + '

    <!--RerunMode: 1 write to DB, 2 write to DB and add to RUN export/-->
    <add key="RerunMode" value="0"/>'

$filename="C\temp\Software.exe.config"

[IO.File]::ReadAllText($filename)| Where{$_ -notlike "*$texttoadd*"} | ForEach{$_.Replace($pattern,$textToAdd) | Set-Content $filename -Force}
Sign up to request clarification or add additional context in comments.

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.