2

如果我需要将一个布尔值从 VSTS 传递到 powershell 脚本以在 CD 中进行部署。我收到以下错误:

无法将值“System.String”转换为类型“System.Boolean”。布尔参数仅接受布尔值和数字,例如 $True、$False、1 或 0。

我将来自 VSTS 的参数作为内联脚本传递-ClientCertificateEnabled "$(ClientCertificateEnabled)"

template.json并在使用中复制值replacetoken.ps1via parameters.local.jason

参数.local.jason

"clientCertEnabled": {
      "value": "{{clientCertificateEnabled}}"
    },

替换令牌.ps1

[Parameter(Mandatory=$true)]
    [bool]
    $ClientCertificateEnabled

$depParametersFile = $depParametersFile.Replace('{{clientCertificateEnabled}}', $ClientCertificateEnabled)

部署.ps1

[Parameter(Mandatory=$true)]
  [bool]
  $ClientCertificateEnabled

模板.json

"clientCertEnabled": {
      "type": "bool",
      "defaultValue": true,
      "metadata": {
        "description": "Indicates if client certificate is required on web applications on Azure."
      }
    }

 "clientCertEnabled": "[parameters('clientCertEnabled')]"
4

2 回答 2

3

假设您正在编写分布式任务,VSTS/AzureDevOps 会将所有参数作为字符串传递。您需要声明您的 ps1 参数块以接受字符串并在内部转换它们。

我没有使用 PowerShell 任务来调用脚本(仅内联脚本),所以我不知道它是如何传递参数的。假设它执行相同的字符串传递是安全的。

param
(
    [string]$OverwriteReadOnlyFiles = "false"
)

我写了一个 Convert-ToBoolean 函数来处理转换并调用它。

[bool]$shouldOverwriteReadOnlyFiles = Convert-ToBoolean $OverwriteReadOnlyFiles

函数定义为:

<#
.SYNOPSIS 
    Converts a value into a boolean
.DESCRIPTION 
    Takes an input string and converts it into a [bool]
.INPUTS
    No pipeline input.
.OUTPUTS
    True if the string represents true
    False if the string represents false
    Default if the string could not be parsed
.PARAMETER StringValue
    Optional.  The string to be parsed.
.PARAMETER Default
    Optional.  The value to return if the StringValue could not be parsed.
    Defaults to false if not provided.
.NOTES
.LINK
#>
function Convert-ToBoolean
(
    [string]$StringValue = "",
    [bool]$Default = $false
)
{
    [bool]$result = $Default

    switch -exact ($StringValue)
    {
         "1"     { $result = $true;  break; }
         "-1"    { $result = $true;  break; }
         "true"  { $result = $true;  break; }
         "yes"   { $result = $true;  break; }
         "y"     { $result = $true;  break; }
         "0"     { $result = $false; break; }
         "false" { $result = $false; break; }
         "no"    { $result = $false; break; }
         "n"     { $result = $false; break; }
    }

    Write-Output $result
}
于 2018-11-28T14:12:07.590 回答
0

我设法通过以下更改解决了这个问题,并将所有 ps1 文件中的布尔类型恢复为字符串。

更改parameters.local.json如下(只是删除了双引号)

"clientCertEnabled": {
      "value": {{clientCertificateEnabled}}
    },

因此,执行后进行上述更改replacetoken.ps1 parameters.local.json将如下所示

"clientCertEnabled": {
      "value": true
    }, 
于 2018-11-29T10:04:01.803 回答