PowerShell脚本无法捕获HTTP请求错误响应头问题求助
解决PowerShell捕获HTTP错误响应头为空的问题
问题核心原因
你遇到的问题源于HttpWebResponse的Headers是WebHeaderCollection类型,无法直接用GetEnumerator()遍历,必须通过AllKeys属性获取所有头名称后再逐个取值。
具体修复步骤
- 修正错误日志的语法问题
原脚本中Log-Message "Error Response: $_.ErrorRecord.Exception"存在语法错误,需改为:
Log-Message "Error Response: $($_.ErrorRecord.Exception)"
- 重构错误响应头的获取逻辑
将catch块中遍历响应头的代码替换为以下逻辑,确保能正确读取所有响应头:
Log-Message "Error Response Headers:" if ($ErrorResponse -and $ErrorResponse.Headers) { foreach ($headerKey in $ErrorResponse.Headers.AllKeys) { $headerValue = $ErrorResponse.Headers.Get($headerKey) Log-Message "$headerKey: $headerValue" } } else { Log-Message "No error response headers available." }
完整修正后的脚本
# Define the log file path $logFilePath = "https_test_connection_log.txt" $apiUrl = "你的目标API地址" # 替换为实际请求URL # Function to log messages with a timestamp function Log-Message { param ( [string]$Message ) $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss" Add-Content -Path $logFilePath -Value "$timestamp - $Message" } # Send a GET request to the API try { # Make the HTTP GET request $response = Invoke-WebRequest -Uri $apiUrl -Method Get -ErrorAction Stop # Log successful response details Log-Message "Request to $apiUrl successful." # Log response headers if they are available if ($response.Headers -ne $null) { Log-Message "Response Headers:" foreach ($header in $response.Headers.GetEnumerator()) { Log-Message "$($header.Key): $($header.Value)" } } else { Log-Message "No headers found in the response." } # Log the response body (handle non-JSON content) try { $responseBody = $response.Content | ConvertTo-Json -Compress -ErrorAction Stop Log-Message "Response Body: $responseBody" } catch { Log-Message "Response Body: $($response.Content)" } } catch { # Log the error message $errorMessage = "Error: $($_.Exception.Message)" Log-Message $errorMessage # Correctly log the error record exception Log-Message "Error Response: $($_.ErrorRecord.Exception)" # Check if an error response is available $ErrorResponse = $_.Exception.Response if ($ErrorResponse) { # Log the error response body if available try { $ErrorContent = (New-Object System.IO.StreamReader($ErrorResponse.GetResponseStream())).ReadToEnd() Log-Message "Error Response Body: $ErrorContent" } catch { Log-Message "Failed to read error response body." } # Properly retrieve error response headers Log-Message "Error Response Headers:" foreach ($headerKey in $ErrorResponse.Headers.AllKeys) { $headerValue = $ErrorResponse.Headers.Get($headerKey) Log-Message "$headerKey: $headerValue" } } else { Log-Message "No error response object available." } }
额外优化说明
- 增加了响应体转JSON的异常捕获,避免非JSON内容导致脚本中断
- 简化了错误响应对象的获取路径,直接使用
$_.Exception.Response更简洁 - 对错误响应体的读取操作增加了异常处理,提升脚本稳定性
内容的提问来源于stack exchange,提问作者Preethi Ravi
相关产品推荐
相关产品推荐

