将 bool 参数从 VSTS 传递到 Powershell 脚本

Pass bool param from VSTS to Powershell script

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

Cannot convert value "System.String" to type "System.Boolean". Boolean parameters accept only Boolean values and numbers, such as $True, $False, 1 or 0.

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

并通过 parameters.local.jason.

使用 replacetoken.ps1 替换 template.json 中的值

parameters.local.jason

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

replacetoken.ps1

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

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

部署。ps1

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

template.json

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

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

假设您正在编写分布式任务,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
}

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

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

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

所以在执行 replacetoken.ps1 之后进行上述更改 parameters.local.json 将如下所示

"clientCertEnabled": {
      "value": true
    },