asp
asp

Reputation: 855

Problem with Replacing line string in XML file format file(.Config file) with Powershell

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;

Upvotes: 1

Views: 302

Answers (2)

michiel Thai
michiel Thai

Reputation: 597

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

Upvotes: 0

zett42
zett42

Reputation: 27806

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"'

Upvotes: 2

Related Questions