Как правильно проверить значение ErrorVariable поддельного CmdLet? - PullRequest
0 голосов
/ 04 июля 2018

Мы пытаемся проверить значение в ErrorVariable из Invoke-Command в тесте Pester. Но по той или иной причине -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()] она все еще не заполнена. Чего нам здесь не хватает?

1 Ответ

0 голосов
/ 24 января 2019

Вы должны использовать 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'
    }
}
...