Here's how I would go about it. First, when you need to get the entire contents of a file for purposes such as replacing text in multiple lines, do not use Get-Content . Use [IO.file]::ReadAllText() .
Then use the -replace operator, for example:
[IO.File]::ReadAllText("$pwd\foo.sql") -replace ' '(?s).*?(USE \[\$\(DatabaseName\)\].*)$',"foo'n'$1" > foo.sql
Here I replace the initial text with "foo". Also note that to get the regular expression used by -replace to match between newline, I add single line mode to the regular expression (?s) .
Mjolinor raises a good question when the replacement text contains characters that can be interpreted as special regular expression variables, for example, $1 , $2 , etc. Although you can use [regex]::escape() to exit the regular expression, there is still PowerShell code that will interpret $<something> as a variable or the beginning of a subexpression. In this case, itβs quite simple to work around, just grabbing the part you want to keep using the -replace operator, and then adding new text in the second step, for example:
$keep = [IO.File]::ReadAllText("$pwd\foo.sql") -replace ' '(?s).*?(USE \[\$\(DatabaseName\)\].*)$','$1' $newText + $keep > foo.sql
Please note that when replacing in this case I use single quotes around $1 , which prevents PowerShell from interpreting any special PowerShell characters. This is like a literal line in C #.
source share