【问题标题】:How to fail the build from a PowerShell task in TFS 2015如何使 TFS 2015 中的 PowerShell 任务的构建失败
【发布时间】:2015-12-28 22:48:17
【问题描述】:

我正在尝试使 PowerShell 脚本中的某个结果使构建过程失败,但它对我不起作用。我正在使用 TFS 2015 中的新构建操作并尝试了以下选项:

我确实在步骤的日志窗口中看到了红色文本,并且在构建概述中标记了“问题”,但构建结果仍然是绿色:“构建成功”

我想使用脚本中的失败来使构建失败,从而使用失败构建的警报发送电子邮件。

编辑:包括 PS 脚本:

Param(
  [string]$url
)

if ($url -eq '')
{
    #use default value
    $url = 'https://myurl.com'
}

$req = [system.Net.WebRequest]::Create($url)
$req.Timeout = 60000 * 5 # = 5 minutes
try
{
    Write-Host "Try to get response from url:" $url
    $res = $req.GetResponse()
    Write-Host "Closing the connection"
    $req.Close() # close the connection
} 
catch [System.Net.WebException] 
{
    Write-Host "Got an exception"    
    Write-Host "##vso[task.logissue type=error;]Exception: " $_.Exception

    if ($_.response) # try to close the connection
    {
        $_.response.Close();    
    }
    $res = $_.Exception.Response
}
$printCode=[int]$res.StatusCode

Write-Host "Result StatusCode:" $res.StatusCode "(" $printCode ")"
If ([int]$res.StatusCode -eq 200)
{
    Write-Host "##vso[task.complete result=Succeeded;]Done"
}
Else
{
    Write-Host "##vso[task.logissue type=error;]Test error: " $res
    Write-Host "##vso[task.complete result=Failed;]Error testing if demo site is up"
    exit 1
}

【问题讨论】:

  • 您能分享您的 PowerShell 脚本以便我们重现吗?
  • 我已编辑问题以包含脚本

标签: powershell tfs-2015


【解决方案1】:

我创建了一个非常简单的脚本:

 Write-Error ("Some error")
 exit 1

将此保存为 PowerShell 脚本。创建一个新的 Empty Build 定义并仅添加一个指向您的脚本的 PowerShell 任务。当我这样做时,我得到一个失败的构建并出现以下错误:

2015-12-30T10:27:29.4872452Z . 'C:\a\1\s\script.ps1' 
2015-12-30T10:27:29.6780242Z Executing the following powershell script. (workingFolder = C:\a\1\s)
2015-12-30T10:27:29.6790500Z C:\a\1\s\script.ps1 
2015-12-30T10:27:33.8017820Z ##[error]C:\a\1\s\script.ps1 : Some error
2015-12-30T10:27:33.8027833Z ##[error]At line:1 char:1
2015-12-30T10:27:33.8037819Z ##[error]+ . 'C:\a\1\s\script.ps1'
2015-12-30T10:27:33.8037819Z ##[error]+ ~~~~~~~~~~~~~~~~~~~~~~~
2015-12-30T10:27:33.8047816Z ##[error]    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
2015-12-30T10:27:33.8047816Z ##[error]    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,script.ps1
2015-12-30T10:27:33.8057887Z ##[error] 
2015-12-30T10:27:33.8057887Z ##[error]Process completed with exit code 1 and had 1 error(s) written to the error stream.

与您的脚本的主要区别在于将 Write-Error 与出口 1 结合使用。

【讨论】:

  • 谢谢 Wouter,这是我错过的简单解决方案。经过一些测试,我发现您可以使用 exit 1 Write-Error 使任务失败。
  • 不是是一个很好的解决方案,因为它会将信息强制写入日志(这对于一个人来说可能很难理解。任务的失败应该独立于任何要求与日志内容相关!
  • @DavidV.Corbin Rob 要求通过 PowerShell 脚本使构建失败。失败的唯一原因是从脚本返回退出代码并将其推送到日志。或者你不想记录你的错误吗?
猜你喜欢
  • 2018-05-12
  • 1970-01-01
  • 2023-03-08
  • 2016-03-06
  • 2016-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-04
相关资源
最近更新 更多