使用Powershell将变量值传递到Jenkins文件中的不同本地作用域

问题描述 投票:2回答:1

我正在开发一个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”的新变量,该变量保存最后一个文件夹名称的值,但是当我转到脚本的下一部分时,需要再次更改目录,testfile变量未创建,并且在尝试检索其值时会引发异常。

我想要做的就是获取最后创建的文件夹的名称,并将其传递给脚本的这一部分,以便更改为新的目录路径。

dir("C:\\Jenkins\\workspace\\QA-Test-Pipeline\\iGCAutomation.Runner\\Reports\\" + testFile + "\\")

我在网上尝试了很多解决方案,但似乎没有任何效果。 Groovy沙箱中的Powershell并不总是像我期望的那样工作。

powershell jenkins-pipeline jenkins-groovy
1个回答
0
投票

不要多次运行powershell,而是将所有脚本连接在一起并执行powershell一次。每次powershell完成时,所有变量都将被删除。

解:

  1. 创建一个名为Copy-NUnitResults.ps1的文件: # Filename: Copy-NUnitResults.ps1 $reportsSrcDir = 'C:\Jenkins\workspace\QA-Test-Pipeline\iGCAutomation.Runner\Reports' $reportDestDir = 'C:\Jenkins\workspace\QA-Test-Pipeline\iGCAutomation.Runner\Reports\NUnitXmlReport' 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
  2. 将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' } }
© www.soinside.com 2019 - 2024. All rights reserved.