Set-Location "C:\thisDirDoesNotExist"
If(-not $?)
{
Write-Error -Message "error"
Exit 1
}
如何模拟命令失败?在上面的代码中,Set-Location命令将出错并出现非终止错误。 $?变量将设置为false,并输出错误消息,脚本将退出。
如何模拟Set-Location命令来设置$?变量为false?
答案 0 :(得分:0)
您可以使用-ErrorVariable
参数。在以下示例中,$locationError
cmdlet失败时将设置变量Set-Location
:
Set-Location "C:\" -ErrorVariable locationError
If($locationError)
{
Write-Error -Message "error"
Exit 1
}
现在您要做的就是将$locationError
设置为$true
以模拟您的失败。
答案 1 :(得分:0)
您可以使用Throw
强制执行您想要的任何错误。 $? Throw
之后将为False。
答案 2 :(得分:0)
通常情况下,产生错误的模拟器会通过测试来验证您是否收到错误,如下所示:
Describe 'mock an error' {
Context 'terminating error' {
Mock -CommandName Set-Location -MockWith {Write-Error 'My Error' -ErrorAction 'Stop'}
it 'should throw' {
{Set-Location -Path .\foo -ErrorAction Stop} | should throw 'My Error'
}
}
Context 'non-terminating error' {
Mock -CommandName Set-Location -MockWith {Write-Error 'My Error' }
it 'should throw' {
{Set-Location -Path .\foo -ErrorVariable slError
$Global:slError=$slError} | should not throw
$global:slError.count |should be 1
$Global:slError[0].Exception.Message | should be 'My Error'
}
}
}
Describing mock an error Context terminating error [+] should throw 551ms Context non-terminating error Write-Error 'My Error' : My Error At C:\Program Files\WindowsPowerShell\Modules\Pester\3.4.0\Functions\Mock.ps1:1056 char:9 + & $___ScriptBlock___ @___BoundParameters___ @___ArgumentList_ ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException [+] should throw 164ms