PowerShell 시도/잡기/마침내
최근에 잘 작동하는 PowerShell 스크립트를 작성했습니다. 그러나 스크립트를 업그레이드하고 오류 확인/처리를 추가하고자 합니다. 그러나 첫 번째 장애물에서 어려움을 겪고 있습니다.왜 다음 코드가 작동하지 않습니까?
try {
Remove-Item "C:\somenonexistentfolder\file.txt" -ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException] {
"item not found"
}
catch {
"any other undefined errors"
$error[0]
}
finally {
"Finished"
}
두 번째 캐치 블록에 오류가 잡혔습니다. 출력을 확인할 수 있습니다.$error[0]
. 당연히 첫 번째 블록에서 잡고 싶습니다.제가 무엇을 빠뜨리고 있나요?
-ErrorAction Stop
당신을 위해 무언가를 바꾸는 겁니다이것을 추가해보고 어떤 결과를 얻을 수 있는지 확인할 수 있습니다.
Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception"
$error[0]
}
그것은 매우 이상합니다.
나는 지나갔습니다.ItemNotFoundException
의 기본 클래스와 다음 배수를 테스트했습니다.catch
무엇이 그것을 잡을 수 있는지 확인하기 위해:
try {
remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
write-host 'RuntimeException'
}
catch [System.SystemException] {
write-host 'SystemException'
}
catch [System.Exception] {
write-host 'Exception'
}
catch {
write-host 'well, darn'
}
결과적으로, 그 결과는'RuntimeException'
. 저도 다른 예외를 두고 시도했습니다.CommandNotFoundException
:
try {
do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
write-host 'CommandNotFoundException'
}
catch {
write-host 'well, darn'
}
그 출력'CommandNotFoundException'
정확하게
다른 곳에서 (다시는 찾을 수 없었지만) 이것과 관련된 문제를 읽었던 것을 어렴풋이 기억합니다.예외 필터링이 제대로 작동하지 않은 경우에는 가장 근접한 위치를 잡을 수 있습니다.Type
그들은 그 다음에 a를 사용할 수 있습니다.switch
. 다음은 그냥 잡습니다.Exception
대신에RuntimeException
, 그러나 그것은switch
모든 기본 유형을 확인하는 나의 첫 번째 예와 동등합니다.ItemNotFoundException
:
try {
Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
switch($_.Exception.GetType().FullName) {
'System.Management.Automation.ItemNotFoundException' {
write-host 'ItemNotFound'
}
'System.Management.Automation.SessionStateException' {
write-host 'SessionState'
}
'System.Management.Automation.RuntimeException' {
write-host 'RuntimeException'
}
'System.SystemException' {
write-host 'SystemException'
}
'System.Exception' {
write-host 'Exception'
}
default {'well, darn'}
}
}
이 글은'ItemNotFound'
, 당연한 대로
언급URL : https://stackoverflow.com/questions/6779186/powershell-try-catch-finally
'it-source' 카테고리의 다른 글
(정규 객체에 대한 포인터와 반대로) 정칙 포인터는 어떤 용도로 사용됩니까? (0) | 2023.10.13 |
---|---|
워드프레스 - 특정메뉴에 대한 wp_nav_메뉴 맞춤형 (0) | 2023.10.13 |
PowerShell의 xargs와 동등한 수준은 얼마입니까? (0) | 2023.10.13 |
mysql에서 쿼리 성능 테스트 (0) | 2023.10.13 |
라인 아이템 우커머스 주문 받기 (0) | 2023.10.13 |