如何从“尝试/捕获”块中仅获得一行错误描述?

问题描述

人们

当无法访问字符串数组中的目标URL或出现其他问题时,我仅需要在下面的代码上获得错误消息的单行说明,就需要帮助。

Clear-Host
$serverName = 'bong.com','bing.com','hotel.com','hotels.com'
$statusCodesAllowed = (200,302,401) #Update this array to include the HTTP status codes that you want to mark as OK.$stat = 0

Foreach ($URL in $serverName) {
    Try {
        $web = Invoke-WebRequest -Uri https://$url -Method Head -UseDefaultCredentials -UseBasicParsing -ErrorAction Stop
        $stat = [int]($statusCodesAllowed -contains $web.statusCode)
        Write-Host "`nURL: $(($URL -split '/')[0]) - $([System.Net.Dns]::GetHostAddresses(($URL -split '/')[0]))" -ForegroundColor Yellow
        Write-Host 'Statistic.Status: '$stat -ForegroundColor Green
        Write-Host 'Message.Status: ' $web.StatusCode $web.StatusDescription -ForegroundColor Green
    }
    
    Catch {
        $statusCode = ($_.Exception.Message.Substring(($_.Exception.Message.IndexOf('(') + 1),3))
        $stat = [int]($statusCodesAllowed -contains $statusCode)
        Write-Host "`nURL: $(($URL -split '/')[0]) - $([System.Net.Dns]::GetHostAddresses(($URL -split '/')[0]))" -ForegroundColor Red
        Write-Warning -Message "Error in resolving $URL"
        Write-Warning 'Message.Status: '$_.Exception.Message -Verbose
    }
    Finally { Remove-Variable serverName,statusCodesAllowed,stat,web,statusCode -ErrorAction SilentlyContinue }
}

预期结果如下所示,将工作URL放在顶部,URL包含错误结果的底部

URL: bing.com - 13.107.21.200 204.79.197.200
Statistic.Status:  1
Message.Status:  200 OK


URL: bong.com - 195.42.193.61
WARNING: Error in resolving bong.com
   'The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.'.


URL: hotel.com - 204.74.99.101
WARNING: Error in resolving hotel.com
   'Unable to connect to the Remote Server'.
 
URL: hotels.com - 104.98.28.184
WARNING: Error in resolving hotels.com
   'The underlying connection was closed: An unexpected error occurred on a receive.'.

我不需要源代码上的错误详细信息。

解决方法

喜欢吗?

Clear-Host
$serverName = 'bong.com','bing.com','hotel.com','hotels.com'
$statusCodesAllowed = (200,302,401) #Update this array to include the HTTP status codes that you want to mark as OK.$stat = 0

$URLarray = $serverName | ForEach-Object {
    Write-Host "Processing:" $_
    Try {
        $web = Invoke-WebRequest -Uri https://$_ -Method Head -UseDefaultCredentials -UseBasicParsing -ErrorAction Stop
        $stat = [int]($statusCodesAllowed -contains $web.statusCode)
        $IPs = $([System.Net.Dns]::GetHostAddresses(($_ -split '/')[0]))
        $StatusCode = $web.StatusCode
        $StatusDesc = $web.StatusDescription
    }
    Catch {
        $statusCode = ($_.Exception.Message.Substring(($_.Exception.Message.IndexOf('(') + 1),3))
        $stat = [int]($statusCodesAllowed -contains $statusCode)
        $IPs = $([System.Net.Dns]::GetHostAddresses(($URL -split '/')[0]))
        $StatusCode = "Error"
        $StatusDesc = $_.Exception.Message
    }
    [pscustomobject]@{URL=$_;IPs=$IPs;Status=$StatusCode;StatusDetail=$StatusDesc}
}

$URLarray

所有结果都放在$ URLarray中-您可以根据需要输出/格式化例如

$URLarray | Sort-Object Status | ForEach-Object {
    Write-Host "`nURL:"$_.URL" - " $_.IPs -ForegroundColor Yellow
    If ($_.Status -ne "Error") {
        Write-Host $_.Status -ForegroundColor Green
        Write-Host $_.StatusDetail -ForegroundColor Green
    }
    Else {
        Write-Host "Error:"  $_.StatusDetail -ForegroundColor Red
    }
}
,

Mia culpa的回应很晚,但是,你知道的。

要获得您在帖子中显示的布局/颜色,即使没有PSCustomerObject(如@Scepticalist所示,它也更优雅并且更适用于发送文件/ csv报表/ Excel等),您可以这样做这个。

Clear-Host
$serverName = 'bong.com','hotels.com' 
Foreach ($URL in $serverName) 
{
    $statusCodesAllowed = (200,401)
    Try 
    {
        $web            = Invoke-WebRequest -Uri https://$url -Method Head -UseDefaultCredentials -UseBasicParsing -ErrorAction Stop
        $stat           = [int]($statusCodesAllowed -contains $web.statusCode)
        $HostName       = Write-Host "`nURL: $(($URL -split '/')[0]) - $([System.Net.Dns]::GetHostAddresses(($URL -split '/')[0]))" -ForegroundColor Yellow
        $HostStatistics = Write-Host 'Statistic.Status: '$stat -ForegroundColor Green
        $HostStatus     = Write-Host 'Message.Status: ' $web.StatusCode $web.StatusDescription -ForegroundColor Green
    }
    
    Catch 
    {
        $statusCode   = ($_.Exception.Message.Substring(($PSItem.Exception.Message.IndexOf('(') + 1),3))
        $stat         = [int]($statusCodesAllowed -contains $statusCode)
        $HostName     = Write-Host "`nURL: $(($URL -split '/')[0]) - $([System.Net.Dns]::GetHostAddresses(($URL -split '/')[0]))" -ForegroundColor Red
        $ErrorMessage = Write-Warning -Message "Error in resolving $URL `n`tMessage.Status: $($PSItem.Exception.Message)" -Verbose
    }
    Finally 
    { 
           Remove-Variable serverName,statusCodesAllowed,stat,web,statusCode,Hostname,HostStatistics,HostStatus,ErrorMessage -ErrorAction SilentlyContinue 
    }
}

# Results
<#
URL: bong.com - 195.42.193.61
WARNING: Error in resolving bong.com 
    Message.Status: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

URL: bing.com - 2620:1ec:c11::200 204.79.197.200 13.107.21.200
Statistic.Status:  1
Message.Status:  200 OK

URL: hotel.com - 204.74.99.101
WARNING: Error in resolving hotel.com 
    Message.Status: Unable to connect to the remote server

URL: hotels.com - 23.62.70.63
WARNING: Error in resolving hotels.com 
    Message.Status: The underlying connection was closed: An unexpected error occurred on a receive.
#>