Updating variables within variables in Powershell

junjoria

I don't know much about Powershell but I try to learn. Can you help me to understand and solve what I want to do:

$string1=""

$complicatedString1 = "This is a complicated $string1"
$complicatedString2 = "$complicatedString1 too"

$string1 = "Test"

$complicatedString1 -> Should state now: This is a complicated Test
$complicatedString2 -> Should state now: This is a complicated Test too.

$string1 = "question"

$complicatedString1 -> Should state now: This is a complicated question
$complicatedString2 -> Should state now: This is a complicated question too.

and so on.

The idea sounds simple: I want to define strings that serve as templates, but with variable content. In this case I want to manipulate $string1 and update $complicatedstring 1 and 2 so that any change of $string1 gets reflected in those strings.

$string1 would change frequently and at the moment I have no approach how get the changed values into those strings. Basically the're just placeholders to wait for being changed.

Theo

I'm not quite sure, but I think your question is about using template strings you can alter using new strings-to-insert.

The most elegant way to do that I think is by making use of the PowerShell -f format operator like this:

# the template strings
$complicatedString1 = "This is a complicated {0}"
$complicatedString2 = "{0} too"

# use the template strings to return new strings
$string1 = $complicatedString1 -f "Test"                # --> "This is a complicated Test"
$string2 = $complicatedString2 -f $string1              # --> "This is a complicated Test too"

$string1 = $complicatedString1 -f "question"            # --> "This is a complicated question"
$string2 = $complicatedString2 -f $string1              # --> "This is a complicated question too"

You can also use the Format method of the string object itself if you like:

$string1 = [string]::Format($complicatedString1, "Test")
$string2 = [string]::Format($complicatedString2, $string1)

which will give you the exact same results

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive