将布尔参数从VSTS传递到Powershell脚本

时间:2018-11-28 06:22:50

标签: powershell azure-devops azure-pipelines-release-pipeline

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

  

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

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

然后通过template.json使用replacetoken.ps1复制parameters.local.jason中的值。

parameters.local.jason

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

replacetoken.ps1

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

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

deploy.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')]"

2 个答案:

答案 0 :(得分:0)

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

我还没有使用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
}

答案 1 :(得分:0)

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

parameters.local.json更改如下(仅删除双引号)

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

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

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