아래 예 catch
에서 -ErrorAction Stop
. 이 경우 완벽하게 작동했습니다.
try
{
Import-Module -ErrorAction Stop -Force nomodule.psm1
}
catch
{
Write-Host -ForegroundColor Red "no module"
$PSItem >> $env:HOMEPATH\AVSUB.log
exit 1
}
그러나 아래의 경우, 내가 사용하지 않은 -ErrorAction Stop
및 catch
블록은 여전히 달렸다.
try
{
$var= broken_function
}
catch
{
Write-Host -ForegroundColor Red "error"
$PSItem >> $env:HOMEPATH\AVSUB.log
exit 1
}
때때로 지정해야하는 이유는 무엇 -ErrorAction Stop
입니까?
PowerShell 에는 종료 및 비 종료 오류가 있습니다.
종료 오류는 cmdlet, 스크립트 또는 프로그램의 실행을 중지하는 오류입니다. 이것은 Try {} Catch {}
필요없이 포착됩니다 -ErrorAction Stop
.
종료되지 않는 오류를 사용하면 PowerShell이 실행을 계속할 수 있습니다. 을 추가하여 잡을 수 있습니다 -ErrorAction Stop
.
다음은 두 가지 함수입니다. 하나는 종료 오류를 생성하고 다른 하나는 종료되지 않는 오류를 생성합니다.
# This will throw a terminating error
function TerminatingErrorExample {
[CmdletBinding()]
Param()
Throw "I can't run like this!"
Write-Host "This message will never be displayed, because it's after the terminating error."
}
# This will write a non-terminating error
function NonTerminatingErrorExample {
[CmdletBinding()]
Param($i = 5)
if ($i -gt 4) {
Write-Error "I expected a value less or equal to 4!"
}
Write-Host "However, I can still continue the execution"
}
넌 호기심 내가 사용하는 이유에 경우 [CmdletBinding()]
기능에, 그 않고, 기능을 지원하지 않기 때문입니다 [<CommonParameters>]
, 그리고 -ErrorAction Stop
CommonParameter입니다.
이제 우리는 그들을 포장 할 수 있습니다 Try {} Catch {}
# Because the function produces a terminating error, the Catch block will run
Try {
TerminatingErrorExample
} Catch {
Write-Host "I got you!"
}
# Since the error here is non-terminating, the catch block won't run
Try {
NonTerminatingErrorExample
} Catch {
Write-Host "You won't see this message"
}
# Now the catch block will run, because we specifically say we want it to stop,
# even on a non-terminating error.
Try {
NonTerminatingErrorExample -ErrorAction Stop
} Catch {
Write-Host "Now you see this message."
}
이것을 실행하면 예상대로 반환됩니다.
I got you!
NonTerminatingErrorExample : I expected a value less or equal to 4!
In Zeile:28 Zeichen:5
+ NonTerminatingErrorExample
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,NonTerminatingErrorExample
However, I can still continue the execution
Now you see this message.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다