Powershell WebScraping和终止异常处理
我正在使用powershell检查多个不同站点的数据。如果站点没有今天的数据,它将抛出NullReferenceException。我希望脚本输出一条没有数据的消息,然后继续到其他站点而不停止 在Java中,我可以简单地尝试/catch/finally,但Powershell的表现并不好Powershell WebScraping和终止异常处理,powershell,exception,web-scraping,nullreferenceexception,Powershell,Exception,Web Scraping,Nullreferenceexception,我正在使用powershell检查多个不同站点的数据。如果站点没有今天的数据,它将抛出NullReferenceException。我希望脚本输出一条没有数据的消息,然后继续到其他站点而不停止 在Java中,我可以简单地尝试/catch/finally,但Powershell的表现并不好 try { $webRequest = Invoke-WebRequest -URI "http://###.##.###.##:####/abcd.aspx?" } catch [S
try {
$webRequest = Invoke-WebRequest -URI "http://###.##.###.##:####/abcd.aspx?"
} catch [System.NullReferenceException]{
Write-Host "There is no data"
}
控制台中会显示完整错误,并且写入主机从未实际出现
Powershell区分终止错误和非终止错误,要使捕获正常工作,需要终止错误
UPD:要获取异常类型,在获得错误后只需执行以下操作:$Error[0]。异常。GetType().FullName
然后你用它来捕捉特定的错误
要继续处理invoke webrequest的特定错误,可以执行以下操作:
try { Invoke-WebRequest "url" }
catch { $req = $_.Exception.Response.StatusCode.Value__}
if ($req -neq 404) { do stuff }
这可能是因为异常可能不是空引用异常。我最初认为这是一个非终止错误,但invoke webrequest会抛出一个终止错误 在这种情况下,您可以简单地尝试(不捕获特定的异常类型) --按操作评论编辑--
try
{
Invoke-WebRequest -URI "http://doc/abcd.aspx?" -ErrorAction Stop
}
catch
{
if($_.Exception.GetType().FullName -eq "YouranticipatedException")
{
Write-Host ("Exception occured in Invoke-WebRequest.")
# You can also get the response code thru "$_.Exception.Response.StatusCode.Value__" if there is response to your webrequest
}
检查我的更新答案我使用您在更新中添加的那一行来检查错误类型。果然,NRE实际上是一个网络例外。因此,如果stop停止程序,我可以将其更改为静默继续,如果我需要循环通过URI数组?通常是的,但不是invoke WebRequest,您是正确的-它不是NRE。然而,我不认为盲目吃特例是最恰当的举措。谢谢你的帮助!然后使用适当的异常类型进行处理,或者简单地使用$\异常.exception.GetType().FullName来获取异常信息。
try
{
Invoke-WebRequest -URI "http://doc/abcd.aspx?" -ErrorAction Stop
}
catch
{
if($_.Exception.GetType().FullName -eq "YouranticipatedException")
{
Write-Host ("Exception occured in Invoke-WebRequest.")
# You can also get the response code thru "$_.Exception.Response.StatusCode.Value__" if there is response to your webrequest
}