user3911596
user3911596

Reputation: 35

PowerShell complex -replace

In PowerShell, how do you replace:

Session("*Logging")="true"

to

Session("*Logging")="false"

The following PowerShell script doesn't work.

get-content E:\WebSystems\Web1\web.config -replace "Session("*Logging")="true"", "Session("*Logging")="false"" | set-content E:\WebSystems\Web1\web.config

It says a bunch of errors:

You must provide a value expression on the right-hand side of the '*' operator.

Unexpected token ... in expression or statement.

Missing argument in parameter list.

Upvotes: 0

Views: 376

Answers (2)

TessellatingHeckler
TessellatingHeckler

Reputation: 28993

Your string quoting is mashed, "Session(" is a string, then *Logging falls outside a string, and PowerShell is trying to deal with it as a multiplication or similar.

If you fixed the quoting, you'd then need to escape Regex special characters to use them as string literals.

And if you fix that, I end up with an error saying get-content doesn't take a -replace parameter.

How about something like:

#short commandlet nanmes
(gc E:\WebSystems\Web1\web.config) |% { $_.replace('Session("*Logging")="true"', 'Session("*Logging")="false"') } | sc E:\WebSystems\Web1\web.config

#long form commandlet names
(Get-Content E:\WebSystems\Web1\web.config) |foreach { $_.Replace('Session("*Logging")="true"', 'Session("*Logging")="false"') } | Set-Content E:\WebSystems\Web1\web.config

This uses foreach to gain access to the string.replace() method, which uses string literals and avoids having to deal with regex escapes, uses single quotes to have a string with double quotes in it, and wraps get-content in parentheses so it reads all content and closes the file and doesn't clash with set-content.

Upvotes: 3

Matt
Matt

Reputation: 46710

If Session("*Logging")="true" is a string literal then some of the characters would needed to be escaped for the match to work. -replace uses regex for string matching and the brackets and astericks have special functions. One thing you could do is use the static method [regex]::escape to do the hard work for you. Other issues are that you need to enclose the Get-Content in brackets else it will treat -replace as a parameter to Get-Content. Also the string are not escaped properly which is what would cause most of your syntax errors. In the variables below I enclose the string in single quotes which is one of several approaches for addressing this.

$match = [regex]::escape('Session("*Logging")="true"')
$replace = 'Session("*Logging")="false"'

(get-content E:\WebSystems\Web1\web.config) -replace $match, $replace | ....

The escaped string looks like Session\("\*Logging"\)="true". You dont need to work about special characters for the replacement string itself.

Upvotes: 3

Related Questions