[英]Azure DevOps PowerShell - Can I build the variable string for a library group variable
PowerShell 5.1 PowerShell 5.1
Library variable name in Group: test.DEV组中的库变量名:test.DEV
Azure DevOps Parameter value: config Azure DevOps 参数值:config
I want to build the variable name test.DEV
and then get the value for it that is stored in Library variables of Azure DevOps.我想构建变量名称
test.DEV
,然后获取存储在 Azure DevOps 的库变量中的值。 For the output, I'm getting the variable name instead of the variable value.对于 output,我得到的是变量名而不是变量值。 Is this even possible?
这可能吗?
steps:
- powershell: |
$myVar = "test.${{ parameters.config }}"
'$($myVar)'
Output: Output:
test.DEV
Expected the value for test.DEV
instead of variable name期望
test.DEV
的值而不是变量名
Yes, it is possible to name a variable, or set a string variable's value, to the name of a variable itself.是的,可以将变量命名或将字符串变量的值设置为变量本身的名称。 I did this on purpose recently as I wanted to create and maintain some dynamically named variables.
我最近故意这样做是因为我想创建和维护一些动态命名的变量。
Using -f
and string placement in that fashion seems to work:以这种方式使用
-f
和字符串放置似乎有效:
WPS 5.1: WPS 5.1:
PS C:\pwsh> $testVar = "test.{0}" -f $psversiontable.CLRVersion
PS C:\pwsh> $testVar
test.4.0.30319.42000
I think it auto-converts to a string here because we're using -f
.我认为它会在这里自动转换为字符串,因为我们使用的是
-f
。
For naming a variable programmatically (or with reserved characters like dots) you can use the New-Variable
cmdlet:要以编程方式命名变量(或使用保留字符,如点),您可以使用
New-Variable
cmdlet:
PS C:\pwsh> New-Variable -name "testVar3.stuff" -value $psversiontable.CLRVersion.toString()
PS C:\pwsh> ${testVar3.stuff}
test.4.0.30319.42000
Here I had to convert it to a string manually, otherwise it sets the value to the specified object.这里我不得不手动将它转换为字符串,否则它会将值设置为指定的 object。
New-Variable
is very useful in this context, I think, because you can do all the string mangling you want for both the -name
and -value
switches without funny escaping. It's a bit verbose, but it's both readable and explicit, which I tend to prefer.我认为
New-Variable
在这种情况下非常有用,因为您可以对-name
和-value
开关进行所有所需的字符串处理,而无需搞笑 escaping。它有点冗长,但它既可读又明确,我倾向于喜欢。
From your description, you need to use nested variable in Azure Pipeline.根据您的描述,您需要在 Azure 管道中使用嵌套变量。
Example: $($myVar)
示例:
$($myVar)
I am afraid that there is no built-in method in Azure pipeline can achieve this.恐怕 Azure 管道中没有内置方法可以实现这一点。
To meet your requirement, you can use the Variable Set task from extension: Variable Toolbox .为了满足您的要求,您可以使用扩展中的变量集任务: Variable Toolbox 。
Here is an example:这是一个例子:
Variable Group:变量组:
Pipeline YAML:管道 YAML:
parameters:
- name: config
type: string
pool:
vmImage: ubuntu-latest
variables:
- group: test
steps:
- task: VariableSetTask@3
inputs:
variableName: 'myVar'
value: '$(test.${{ parameters.config }})'
- powershell: |
echo $(myVar)
Result:结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.