在 Powershell 中更新变量内的变量 [英] Updating variables within variables in Powershell
问题描述
我对 Powershell 了解不多,但我尝试学习.你能帮我理解和解决我想做什么吗:
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.
这个想法听起来很简单:我想定义用作模板但内容可变的字符串.在这种情况下,我想操作 $string1 并更新 $complicatedstring 1 和 2,以便 $string1 的任何更改都反映在这些字符串中.
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 会频繁更改,目前我不知道如何将更改后的值放入这些字符串中.基本上只是等待更改的占位符.
$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.
推荐答案
我不太确定,但我认为您的问题是关于使用模板字符串,您可以使用新的字符串插入进行更改.
I'm not quite sure, but I think your question is about using template strings you can alter using new strings-to-insert.
我认为最优雅的方法是使用 PowerShell -f
格式运算符,如下所示:
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"
如果您愿意,也可以使用字符串 object 本身的 Format
方法:
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
这篇关于在 Powershell 中更新变量内的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!