如何通过PowerShell脚本正确设置变量,然后使用Azure DevOps在另一个变量中使用它?

时间:2020-08-04 20:32:18

标签: azure powershell azure-devops

我有第一个内联PowerShell脚本,其中正在过滤测试项目目录并将其值设置为名为testProjectPath的变量。

- task: PowerShell@2
  displayName: "Get tests path"
  inputs:
    targetType: "inline"
    script: |
      $testpath = Get-ChildItem -Filter *Tests.csproj -Recurse | Select-Object Directory -First 1
      
      Write-Host "##vso[task.setvariable variable=testProjectPath]$testpath"

然后我有第二个脚本,该脚本根据我的Set-Location变量中存在的路径尝试testProjectPath

- task: PowerShell@2
  displayName: "Run mutations"
  inputs:
    targetType: "inline"
    script: |
      Set-Location $env:testProjectPath

但是每次我尝试运行此管道时,都会收到以下错误消息:

@{Directory=D:\a\1\s\Wms.PickingCheck.Tests}
Set-Location : Cannot find drive. A drive with the name '@{Directory=D' does not exist.
At D:\a\_temp\752e8e31-b8ac-4f43-9ee0-248f6b12577c.ps1:4 char:1
+ Set-Location $env:testProjectPath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (@{Directory=D:String) [Set-Location], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetLocationCommand
 

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

在原始脚本中,$testpath的值为@{Directory=xxxxxx}。但是,Set-Location无法识别此格式,Set-Location会将当前工作位置设置为指定位置,这就是为什么会出现错误:

enter image description here

您可以通过添加-Expand作为@AdminOfThings中提到的$testpath = Get-ChildItem -Filter *Tests.csproj -Recurse | Select-Object -Expand DirectoryName -First 1

来修改脚本

enter image description here