首页 > 解决方案 > 在 Powershell 中处理数组(使用 Pester 进行测试)

问题描述

我在理解实现此过程的方式时遇到了一些麻烦。我想在分数中获得总计数,以便如果测试成功通过或失败,可以将其添加到数组中。该数组将计入长度。

这是我的代码作为示例:

#This stores the array of the number of passed and failed test
$passed = @()
$failed = @() 

Describe "Template Syntax" {

    It "Has a JSON template" {        
       $fileLocation = "$here\azuredeploy.json" 
       $fileCheck = $fileLocation | Test-Path

        if ($fileCheck -eq $true) {  $passed = $passed + 1
        Write-Host "1st file exist " }
        if ($fileCheck -eq $false) { $failed = $failed + 1
        Write-Host "1st file does exist" }

        }

        It "Has a parameters file" {        
     $fileLocation ="$here\azuredeploy.parameters*.json"

      $fileCheck = $fileLocation | Test-Path

        if ($fileCheck -eq $true) {  $passed = $passed + 1; 
        Write-Host "2nd file exist "}
        if ($fileCheck -eq $false) {  $failed = $failed + 1
        Write-Host "2nd file does exist" }

        } 

        PrintArgs

        }

function PrintArgs(){
Write-Host -ForegroundColor yellow "Passed: $($passed.Length) Failed: $($failed.Length)"
   }

我可以采取其他方式或其他方法来实现这一目标吗?我知道 pester 会自动执行此操作,但是,我想使用 Powershell 脚本进行测试。

标签: powershellazureazure-powershellpester

解决方案


查看您的代码,您不需要数组来计算分数。不用将$passedand定义$failed为数组,只需将它们设置为起始值为 0 的整数计数器

$passed = $failed = 0

然后,您只需调用函数 PrintArgs()而不是

Write-Host -ForegroundColor yellow "Passed: $passed Failed: $failed"

顺便说一句,要增加一个计数器,你可以简单地做$passed++而不是$passed = $passed + 1

如果您坚持使用数组,您可以$passed = $passed + 1$passed += $true. 通过这样做,您可以向数组添加一个值为 $true 的新元素(或者您认为更合适的任何值。


推荐阅读