-Verbose在PowerShell中不能使用我的Pester测试

时间:2017-04-12 19:21:26

标签: powershell powershell-v3.0 verbose pester

我写了一个pester测试来检查某些文件夹和文件是否存在。 pester测试工作得很好,但如果使用-Verbose选项调用测试,我想包含修复建议。但我似乎无法在实际测试中获得-Verbose参数。

文件夹/文件结构:

Custom-PowerShellModule
    |   Custom-PowerShellModule.psd1
    |   Custom-PowerShellModule.psm1
    \---Tests
            Module.Tests.ps1

以下是pester测试的最重要部分:

$Here = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"

Describe "Module Minimum Requirements Tests.  Use -Verbose for Suggested Fixes" -Tags Module {
  Context "Test:  Verify File Counts = 1" {
    Write-Verbose  "If you receive an error, verify there is only 'ONE' PSD1 File and only 'ONE' PSM1 File."
    It "There is only one PSD1 file" { (Get-ChildItem "$Here\..\" *.psd1).count | Should be 1 }
    It "There is only one PSM1 file" { (Get-ChildItem "$Here\..\" *.psm1).count | Should be 1 }
  }
}

3 个答案:

答案 0 :(得分:2)

根据其他答案,在使用Write-Verbose命令运行脚本时,似乎无法使用Invoke-Pester。我认为这可能是因为使用Invoke-Pester命令意味着脚本被解释而不是由PowerShell引擎直接执行。下一个最佳替代方案是添加If语句,执行与测试相同的检查,然后使用Write-HostWrite-Warning来指示它们是否为负数。我过去偶尔会这样做。

如果直接执行脚本(例如直接运行* .tests.ps1文件),则可以使用-verbose。但是,为此,您需要将[cmdletbinding()]和Param块添加到脚本的顶部:

[cmdletbinding()]
Param()

$Here = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"

Describe "Module Minimum Requirements Tests.  Use -Verbose for Suggested Fixes" -Tags Module {
  Context "Test:  Verify File Counts = 1" {

    Write-Verbose  "If you receive an error, verify there is only 'ONE' PSD1 File and only 'ONE' PSM1 File."

    It "There is only one PSD1 file" { (Get-ChildItem "$Here\..\" *.psd1).count | Should be 1 }
    It "There is only one PSM1 file" { (Get-ChildItem "$Here\..\" *.psm1).count | Should be 1 }
  }
}

答案 1 :(得分:0)

-Verbose switch of Invoke-Pester` cmdlet在测试用例中不可用,您必须明确地传递它以供测试用例访问。

以下是您脚本的示例。

Param([Bool]$Verbose)

Describe "Module Minimum Requirements Tests.  Use -Verbose for Suggested Fixes" -Tags Module {
    Context "Test:  Verify File Counts = 1" {
    Write-Verbose  "If you receive an error, verify there is only 'ONE' PSD1 File and only 'ONE' PSM1 File." -Verbose:$Verbose
    It "There is only one PSD1 file" { (Get-ChildItem "$Here\..\" *.psd1).count | Should be 1 }
    It "There is only one PSM1 file" { (Get-ChildItem "$Here\..\" *.psm1).count | Should be 1 }
   }
}


Invoke-Pester -Script @{Path='path' ; Parameters = @{ Verbose = $True }}

此致 Prasoon

答案 2 :(得分:0)

您也可以在范围内更改VerbosePreference的默认值,而不是将Verbose标志明确传递给测试用例:

$VerbosePreference = $Env:MyVerbosePreference

然后您可以从外部进行控制:

$Env:MyVerbosePreference= 'Continue'
Invoke-Pester ...