我正在开发一个 Jenkins 文件以创建一个测试管道。
我一直在努力寻找以下解决方案:
在Jenkins 文件中,我添加了一个阶段,我想在测试完成后发布 Nunit 报告,但是每次运行都会创建一个标有日期和时间的文件夹,因此始终从列表中选择最后一个文件夹非常重要。我的问题是我正在使用 powershell 命令来检索创建的最后一个文件夹的名称,并在特定的目录路径中执行此命令,如下所示:
stage('Publish NUnit Test Report'){
dir('C:\Jenkins\workspace\QA-Test-Pipeline\iGCAutomation.Runner\Reports') {
powershell 'echo "Set directory"'
powershell 'New-Variable -Name "testFile" -Value (gci|sort LastWriteTime|select -last 1).Name -Scope global'
powershell 'Get-Variable -Name "testFile"'
}
testFile = powershell 'Get-Variable -Name "testFile"'
dir("C:\Jenkins\workspace\QA-Test-Pipeline\iGCAutomation.Runner\Reports\" + testFile + "\") {
powershell 'Get-Location'
powershell 'copy-item "TestResultNUnit3.xml" -destination "C:\Jenkins\workspace\QA-Test-Pipeline\iGCAutomation.Runner\Reports\NUnitXmlReport" -force'
}
dir('C:\Jenkins\workspace\QA-Test-Pipeline\iGCAutomation.Runner\Reports\NUnitXmlReport'){
nunit testResultsPattern: 'TestResultNUnit3.xml'
}
}
正如您所注意到的,我正在尝试创建一个名为"testFile"的新变量,该变量保存最后一个文件夹名称的值,但是当我转到脚本的下一部分时,这需要再次更改目录,测试文件变量不会创建,并且在尝试检索其值时会引发异常。
我想做的只是获取最后一个创建的文件夹的名称并将其传递给脚本的这一部分,以便更改为新的目录路径。
dir("C:\Jenkins\workspace\QA-Test-Pipeline\iGCAutomation.Runner\Reports\" + testFile + "\")
我在网上尝试了很多解决方案,但似乎没有任何效果。Groovy沙盒中的Powershell并不总是像我预期的那样工作。
与其多次运行powershell
,不如将所有脚本连接在一起并仅执行一次powershell
。每次powershell
完成时,都会删除所有变量。
溶液:
-
创建一个名为
Copy-NUnitResults.ps1
的文件:# Filename: Copy-NUnitResults.ps1 $reportsSrcDir = 'C:JenkinsworkspaceQA-Test-PipelineiGCAutomation.RunnerReports' $reportDestDir = 'C:JenkinsworkspaceQA-Test-PipelineiGCAutomation.RunnerReportsNUnitXmlReport' Push-Location $reportsSrcDir $testFile = (gci|sort LastWriteTime|select -last 1).Name Pop-Location Push-Location "$reportsSrcDir$testFile" Copy-Item TestResultNUnit3.xml -Destination $reportDest -Force Pop-Location
-
修改你的 Jenkins 步骤,使其看起来像这样
stage('Publish NUnit Test Report'){ # you may need to put in the full path to Copy-NUnitResults.ps1 # e.g. powershell C:\Jenkins\Copy-NUnitResults.ps1 powershell .Copy-NUnitResults.ps1 dir('C:\Jenkins\workspace\QA-Test-Pipeline\iGCAutomation.Runner\Reports\NUnitXmlReport'){ nunit testResultsPattern: 'TestResultNUnit3.xml' } }