31.10.2025

Powershell istisnaları

Powershell istisnaları (exceptions) uzun konu. Doğrudan söylemek istediğime geleyim. Bir web sayfasına bağlantı yapmaya çalışıyorum, Invoke-WebRequest ile. Bu cmdlet'i bir try-catch bloğuna koyuyorum. 

try {
    Invoke-WebRequest -Uri "https://example.com" -Method Get
}
catch {
    $_.Exception.Response.StatusCode
    $_.Exception.Response.StatusCode.Value__
    $_.Exception
}

catch ile aslında burada olabilecek bütün istisnalar için bir yakalama yaptım. Ama her istisna durumu için ayrı ayrı işlem yapılacaksa bu istisna durumlarını ayrı ayrı incelemek gerekebilir. Örneğin Forbidden (403) dönen bir HTTP response durumu için bir eylemde bulunmak istiyorsak

try {
    Invoke-WebRequest -Uri "https://example.com" -Method Get
}
catch [System.Net.WebException] {
    $_.Exception.Response.StatusCode
    $_.Exception.Response.StatusCode.Value__
    $_.Exception
}

ile System.Net.WebException sınıfı istisna yakalayabilirim. Peki olası bütün istisnaları nasıl öğrenebilirim?

Öncelikle $_ değişkeni catch bloğuna özel, son istisna. $Error değişkeni, mevcut oturumda oluşan bütün istisnaların dizisi. En son istisnaya $Error[0] ile ulaşılabilir. $err ise $Error için bir alias.

Bir istisnanın türünü anlamak için catch bloğunun içinde GetType() kullanılabilir. 

try {
    Invoke-WebRequest -Uri "https://example.com" -Method Get
}
catch {
    $_.GetType().FullName
}

Bu, Forbidden (403) durumunda

System.Net.WebException

döndü. Meşhur sıfır ile bölünme durumu istisnası için

try {
    1/0
}
catch {
    $_.GetType().FullName
}
System.Management.Automation.RuntimeException

döndü. 

Daha iyi bir örnek Powershell yardım sitesinden bulunabilir:

try
{
    Start-Something -Path $path -ErrorAction Stop
}
catch [System.IO.DirectoryNotFoundException],[System.IO.FileNotFoundException]
{
    Write-Output "The path or file was not found: [$path]"
}
catch [System.IO.IOException]
{
    Write-Output "IO error with the file: [$path]"
}
catch
{
    Write-Output "An unexpected error occurred: $_"
}

Burada klasör ve dosya bulunamaması durumları için bir işlem, giriş/çıkış işlemi hataları için başka bir işlem yapılmış. En sonunda da bu iki sınıfa da dahil olmayan işlemler için bir genel yakalama yapılmış.

Daha da iyisi yapılarak istisnaların büyük bir listesi oluşturulmuş

Hiç yorum yok: