Author Posts

April 27, 2015 at 7:10 am

Is it possible to use a backtick to make my text readable in the following statement. My liline for the replace will be long.

.Replace('Host="Detroit1"','Host="Log123#).Replace('Host="Devnver12"','Host="Files132"').Replace('Host="Devnver12"','Host="Files132"')

**************************************************************************************************************************************************************
Is it possible to have a statement like this

$_.Replace('Host="Detroit1"',' Host="Log123#" ') `
.Replace('Host="Devnver12"',' Host="Files132" ')`
.Replace('Host="Devnver12"',' Host="Files132" ')

****************************************************************************************************************************************************************
I I am getting the message below.

+ $_.Replace('Host="Detroit1"',' Host="Log123#" ') '
+ ~
Unexpected token "

Thanks

April 27, 2015 at 7:18 am

It's legal, but it is not legal to have a space between the closing parentheses ) and the period . that comes before the next method name.

April 27, 2015 at 7:38 am

You can also do this without backticks if you put the dot operator at the end of the line. That's one of the freebie line continuation characters that PowerShell gives you, because it knows that it's not a complete expression without something to the right of the dot:

$string = 'I am a string'

$string.Replace('string', 'frog').
        Replace('am', 'found')

April 27, 2015 at 11:46 am

Also, you can break on the parens as if they were a block:

"Hello, there!".
Replace(
    "there",
    "Mikhael"
)

April 27, 2015 at 11:54 am

And since you are chaining the replaces, seems like a good opportunity to loop over sets of replacement terms defined in a hash table. It'll be a lot easier to read and troubleshoot as the number of your replacement terms increases.

$r = @{
    "there" = "Mikheal"
    "Hello" = "Goodbye"
}

$str = "Hello, there!"

ForEach($key in $r.Keys) {
    $str = $str -replace $key, $r[$key]
}

$str

April 27, 2015 at 12:01 pm

Thank you all (Don, Dave & Craig) for your input. This has given a better insight.