2015-04-13 13 views
12

Skytap API (REST) ​​kullanarak bir powershell komut dosyası var. Varsa, hatayı yakalamak istiyorum ve görüntülemeye çalışıyorum.Invoke-RestMethod için Hata İşleme - Powershell

Örneğin, IP değişiyor: IP başka bir yerde kullanılan

Invoke-RestMethod -Uri https://cloud.skytap.com/configurations/XXXXXX/vms/YYYYYY/interfaces/ZZZZZZ?ip=10.0.0.1 -Method PUT -Headers $headers 

, ben 409 Çatışma Hatası alacak (İstek iyi biçimlendirilmiş ancak başka bir kaynak veya izne çakışıyor).

Hata 409 olup olmadığını kontrol etmek ve sonra bunun hakkında başka bir şey yapmak için söyle.

cevap

30

Bu, biraz garip, ancak bildiğim kadarıyla, .NET'in WebRequest ve ConvertFrom-Json (veya beklediğiniz veri formatı) gibi daha karmaşık bir şey yapmadan bildiğim kadarıyla yapmanın tek yolu.

try { 
    Invoke-RestMethod ... your parameters here ... 
} catch { 
    # Dig into the exception to get the Response details. 
    # Note that value__ is not a typo. 
    Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__ 
    Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription 
}