Replace a value with regular expressions in PowerShell

I have a value assigned to variable, trying to add this value to another varible inside some regular expressions.

$displayName= "revison"

$updateddisplayName = "updateddisplayName = "${$displayName}""

Write-Host "$updateddisplayName"

I am able to get the variable value with below but not getting expected result. Tried with some different regular expressions as well.

$updateddisplayName = "updateddisplayName = $displayName"

I tried with replace but looks use case of Regex is almost same so did not worked.

(Get-Content -Path $PSScriptRoot/text.txt -Raw) -Replace 'setDisplayName.*', 'updateddisplayName = "${$displayName}"' | Set-Content $PSScriptRoot/text.txt

OutPut expected is updateddisplayName = "${revison}"


  • You need to escape the " double-quotes, either by doubling them or with a backtick, and then you need to escape the first $ - otherwise PowerShell will see ${$displayName} and attempt to resolve and expand the value of a variable with the literal name $displayName:

    $displayName= "revison"
    $updateddisplayName = "updateddisplayName = ""`${$displayName}"""