You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将含$()/$[]表达式的JSON导入Azure DevOps变量组

问题描述

需要将包含$()或$[]表达式的JSON文件导入Azure DevOps库变量组,使用提供的PowerShell脚本时,只要变量值包含$(env)这类表达式就会报错:

az : --description was unexpected at this time.
At line:22 char:5
+     az pipelines variable-group create --name $groupName --variables  ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (--description w...d at this time.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError

移除表达式后脚本可正常运行,需解决含表达式的JSON导入问题。

问题原因

PowerShell会将$(env)识别为子表达式语法,尝试解析执行该表达式(但env并非有效命令/变量),导致生成的Azure CLI参数格式混乱,最终触发错误。

解决方案

对变量值中的$进行转义,使用PowerShell的转义符`(反引号)将$替换为`$,避免PowerShell解析这些表达式,直接传递原始字符串给Azure CLI。

修改脚本中构建variablesString的部分,完整代码如下:

$jsonFilesDirectory = "C:\variables" 
$jsonFiles = Get-ChildItem -Path $jsonFilesDirectory -Filter *.json 
foreach ($json in $jsonFiles) 
{ 
    $jsonnames = $json.Name 
    $jsonContent = Get-Content -Path "C:\variables\$jsonnames" | Out-String 

    $variableGroup = $jsonContent | ConvertFrom-Json

    $groupName = $variableGroup.name
    $description = $variableGroup.description
    $variablesObject = $variableGroup.variables
    
    $variablesHashtable = @{}
    foreach ($property in $variablesObject.PSObject.Properties) {
        $variableName = $property.Name
        $variableValue = $property.Value.value
        $variablesHashtable[$variableName] = $variableValue
    }
    
    # 转义变量值中的$符号,避免PowerShell解析子表达式
    $variablesString = $variablesHashtable.GetEnumerator() | ForEach-Object { 
        $escapedValue = $_.Value -replace '\$', '`$'
        "$($_.Key)=$escapedValue" 
    } 
    
    # 创建变量组
    az pipelines variable-group create --name $groupName --variables $variablesString --description $description --detect false --org 'https://dev.azure.com/<org>' --project '<project>'
}

修改后,PowerShell会将test-$(env)转义为test-$(env)`,传递给Azure CLI时会被正确识别为原始表达式字符串,成功创建包含表达式的变量组。

内容的提问来源于stack exchange,提问作者albbla91

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 10:20:36