1

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

4
  • ${revison} is valid variable and variables can expand in ", you need to use ' (single quotes) instead $updateddisplayName = 'updateddisplayName = "${$displayName}"' Commented Jul 18, 2023 at 14:24
  • 1
    @SantiagoSquarzon This was not working. the out put of this is updateddisplayName = "${$displayName}" but I am looking for an out put with displayname value as well like updateddisplayName = "${revison}"
    – Hemanth
    Commented Jul 18, 2023 at 14:31
  • Using concatenation of single-quoted strings might be more readable and avoids the escaping hassles: "$updateddisplayName = 'updateddisplayName = "${' + $displayName + '}"'
    – zett42
    Commented Jul 18, 2023 at 14:39
  • So you actually want to expand the value of $displayName while also keeping ${ and } if so then Mathias's answer solves that problem Commented Jul 18, 2023 at 14:50

1 Answer 1

2

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.