首页 > 解决方案 > 如何使用powershell在构建管道中验证天蓝色任务中的空字段

问题描述

我正在天蓝色构建管道中创建新的 VSTS/TFS 扩展。在该扩展中,一个字段接受文件路径,它是可选字段。在 powershell 脚本中,我想验证该字段,如果没有提供输入,那么我必须忽略,否则我必须检查输入是否是 .config 文件的路径。

$ConfigFileName = Get-VstsInput -Name 'ConfigFilePath'
 if (!(Test-Path $ConfigFileName))
      {

          Write-Host "Configuration file doesn't exist."
          "##vso[task.complete result=Failed]" 

          throw "Configuration file doesn't exist."
      }

      if([IO.Path]::GetExtension($ConfigFileName) -ne '.config')
      {
         Write-Host "Invalid configuration file.File type must be of .config"
         "##vso[task.complete result=Failed]"
         throw "Invalid configuration file.File type must be of .config"
      }

我已经像上面一样进行了验证,但是当用户没有提供任何输入时,$ConfigFileName 变量也填充了映射路径,即 $ 值。如何检查提供给该字段的输入是否为空?

标签: azure-pipelines-release-pipelineazure-pipelines-build-taskbuild-pipeline

解决方案


对于 filePath 类型的输入字段,默认值为源目录(Build.SourcesDirectory,例如 D:\a\1\s)。因此,您可以检查该值是否不等于源目录。

例如:

{
  "name": "filePathSelect",
  "type": "filePath",
  "label": "test select Path",
  "required": false,
  "defaultValue": "",
  "helpMarkDown": "test select path"
}

电源外壳:

Write-Host "get select file path value"
$fileSelectPathValue = Get-VstsInput -Name filePathSelect
Write-Host "select file path value is $fileSelectPathValue"
Write-Host "default path $env:Build_SourcesDirectory"
if([string]::IsNullOrEmpty($fileSelectPathValue)){
                Write-Host "Selected File path is empty"    
}
elseif(($fileSelectPathValue -eq $env:Build_SourcesDirectory) -or !(Test-Path $fileSelectPathValue))
{           
                    Write-Host "select path is invalid"
}
else
{
                Write-Host "select path is valid"
}

如果输入类型是字符串,那么您只需要检查值是 null 还是 empty [string]::IsNullOrEmpty


推荐阅读