You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Pester模拟PowerShell的$PSVersionTable变量?附代码示例

用Pester模拟PowerShell的$PSVersionTable变量

当然可以!你完全可以用Pester来模拟$PSVersionTable变量,从而测试你的PowerShell版本检查逻辑。下面结合你的代码给出具体的实现方案:

被测试脚本(Testcase.ps1)

先确认你的被测试函数逻辑没问题,这里保留你原有的代码:

trap [Exception] { write-error $("TRAPPED: " + $_) exit 1 }
function Check_Powershell_Version {
    $PSVersion = $PSVersionTable.PSVersion.Major
    if ($PSVersion -lt 3){
        echo "Current version is not compatible. Please upgrade powershell"
    }
}

测试脚本(Testcase.Tests.ps1)

修改并补全你的测试脚本,通过覆盖全局的$PSVersionTable变量来模拟不同的PowerShell版本场景:

$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut" # 导入被测试的脚本

Describe "Check_Powershell_Version 功能测试" {
    # 保存原始的$PSVersionTable,测试结束后恢复
    $originalPSVersionTable = $global:PSVersionTable

    AfterAll {
        $global:PSVersionTable = $originalPSVersionTable
    }

    Context "当PowerShell版本低于3时" {
        BeforeEach {
            # 在测试作用域中模拟低版本的PSVersionTable
            $global:PSVersionTable = [PSCustomObject]@{
                PSVersion = [Version]"2.0"
            }
        }

        It "应该输出兼容性警告" {
            $output = Check_Powershell_Version
            $output | Should -Be "Current version is not compatible. Please upgrade powershell"
        }
    }

    Context "当PowerShell版本为3或更高时" {
        BeforeEach {
            # 模拟高版本的PSVersionTable
            $global:PSVersionTable = [PSCustomObject]@{
                PSVersion = [Version]"5.1"
            }
        }

        It "不应该输出任何警告" {
            $output = Check_Powershell_Version
            $output | Should -BeNullOrEmpty
        }
    }
}

关键说明

  • 覆盖全局变量:因为$PSVersionTable是PowerShell的全局自动变量,所以需要用$global:前缀来在测试作用域中修改它,这样的修改只会在测试期间生效。
  • 恢复原始值:在AfterAll块中保存并恢复原始的$PSVersionTable,避免测试修改影响当前PowerShell会话的环境。
  • 场景化测试:用Context块区分不同的版本场景,BeforeEach在每个测试用例前设置对应的模拟版本,让测试逻辑更清晰。

内容的提问来源于stack exchange,提问作者Sakshi Rawal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:17:47