1

Objective: To find a line in server.config file and replace with some other value using powershell

String that I am trying to find in that file:

<add key="ReportServerUrl" value="http://ADEVSQL14\SQL2016_INS1/ReportServer"></add>

String to be replaced:

<add key="ReportServerUrl" value="http://ADEVSQL14/SQL2016_INS1/ReportServer"></add>

What I tried:

$filename = Get-Content "C:\target\Server.Config"
$filename -replace "<add key="ReportServerUrl" value="http://ADEVSQL14\SQL2016_INS1/ReportServer"></add>", "<add key="ReportServerUrl" value="http://ADEVSQL14/SQL2016_INS1/ReportServer"></add>"

Error which I get:

    ...  "<add key="ReportServerUrl" value="http://ADEVSQL14\SQL2016_INS1/Rep 
Unexpected token 'ReportServerUrl" value="http://ADEVSQL14\SQL2016_INS1/ReportServer"></add>"' in expression o statement.

Additional Inputs: Though I want use this functionality as part of powershell step in Azure devops pipeline, I am trying it out at command line getting similar error

Can some one suggest please.

Update1:

Tried below at command line, it executes successfully but its not getting replaced.

  $filename = Get-Content "C:\target\Server.config" -Raw
$filename -replace '"http://ADEVSQL14\SQL2016_INS1/ReportServer"','"http://ADEVSQL14/SQL2016_INS1/ReportServer"'|Set-Content -Path C:\target\Server.config;
1
  • 1
    Is not a good idea to peek and/or poke directly into a serialized (xml) string (it might even expose a security hole). Instead use the related parsers. See also: Powershell regex for replacing text between two strings Commented Dec 25, 2020 at 17:11

2 Answers 2

2

From the docs:

<input> -replace <regular-expression>, <substitute>

This means you can't search for a literal string that contains characters that have special meaning in a regular expression, like the backslash. Such characters must be escaped by inserting a backslash in front of them.

Try this:

$filename -replace '"http://ADEVSQL14\\SQL2016_INS1/ReportServer"','"http://ADEVSQL14/SQL2016_INS1/ReportServer"'

You can also use Regex.Escape() method to automatically escape all special characters:

$searchStr = '"http://ADEVSQL14\SQL2016_INS1/ReportServer"'
$searchStrEscaped = [Regex]::Escape( $searchStr )

$filename -replace $searchStrEscaped, '"http://ADEVSQL14/SQL2016_INS1/ReportServer"'
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @zett42 .. that escape character \ does the trick
0

A better practice is to use #{Tokens}# as values in the source code, and then use a replacetokens step during a pipeline.

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.