gpt4 book ai didi

powershell - 如何正确测试模拟 CmdLet 的 ErrorVariable 值?

转载 作者:行者123 更新时间:2023-12-02 23:37:43 24 4
gpt4 key购买 nike

我们试图在 Pester 测试中检查 Invoke-CommandErrorVariable 中的值。但出于某种原因,-ErrorVariable 未实例化。

Describe 'test ErrorVariable' {
Mock Invoke-Command {
#[CmdletBinding()]
#param (
# [String[]]$ComputerName,
# $ScriptBlock
#)

$ErrorId = 'NetworkPathNotFound,PSSessionStateBroken'
$TargetObject = 'UnknownHost'
$ErrorCategory = [System.Management.Automation.ErrorCategory]::OpenError
$ErrorMessage = "Connecting to remote server $TargetObject failed with the following error message : WinRM cannot process the request. The following error occurred while using Kerberos authentication: Cannot find the computer $TargetObject. Verify that the computer exists on the network and that the name provided is spelled correctly. For more information, see the about_Remote_Troubleshooting Help topic."
$Exception = New-Object -TypeName System.InvalidOperationException -ArgumentList $ErrorMessage
$ErrorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord -ArgumentList $Exception, $ErrorId, $ErrorCategory, $TargetObject

$ErrorRecord
}

it 'should be green because it should contain the TargetObject' {
Invoke-Command -ComputerName TestComputer -ScriptBlock {1} -ErrorVariable ConnectionError
$ConnectionError.TargetObject | Should -Be 'UnknownHost'
}
}

即使添加了 [CmdletBinding()] 选项,它仍然没有被填充。我们在这里缺少什么?

最佳答案

你应该使用Write-Error:

Describe 'test ErrorVariable' {
Mock Invoke-Command {
$ErrorId = 'NetworkPathNotFound,PSSessionStateBroken'
$TargetObject = 'UnknownHost'
$ErrorCategory = [System.Management.Automation.ErrorCategory]::OpenError
$ErrorMessage = "Connecting to remote server $TargetObject failed with the following error message : WinRM cannot process the request. The following error occurred while using Kerberos authentication: Cannot find the computer $TargetObject. Verify that the computer exists on the network and that the name provided is spelled correctly. For more information, see the about_Remote_Troubleshooting Help topic."
$Exception = New-Object -TypeName System.InvalidOperationException -ArgumentList $ErrorMessage

Write-Error -ErrorId $ErrorId -TargetObject $TargetObject -Category $ErrorCategory -Message $ErrorMessage -Exception $Exception
}

it 'should be green because it should contain the TargetObject' {
Invoke-Command -ComputerName TestComputer -ScriptBlock {1} -ErrorVariable ConnectionError -ErrorAction SilentlyContinue
$ConnectionError.TargetObject | Should -Be 'UnknownHost'
}
}

关于powershell - 如何正确测试模拟 CmdLet 的 ErrorVariable 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51169264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com