Backtick

This topic contains 5 replies, has 4 voices, and was last updated by Profile photo of Mikhael Kaendera Mikhael Kaendera 2 years ago.

  • Author
    Posts
  • #24726
    Profile photo of Mikhael Kaendera
    Mikhael Kaendera
    Participant

    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

  • #24727
    Profile photo of Don Jones
    Don Jones
    Keymaster

    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.

  • #24728
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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')
    
  • #24735
    Profile photo of Craig Duff
    Craig Duff
    Participant

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

    "Hello, there!".
    Replace(
        "there",
        "Mikhael"
    )
  • #24736
    Profile photo of Craig Duff
    Craig Duff
    Participant

    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
  • #24738
    Profile photo of Mikhael Kaendera
    Mikhael Kaendera
    Participant

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

You must be logged in to reply to this topic.