请求修改PowerShell脚本:批量检测URL并导出HTTP状态至CSV
Hi Rajiv, nice to help you scale up your URL checking workflow! Let's revamp your script to handle bulk URLs from either a TXT or CSV file, and export all results neatly to a CSV including status codes, descriptions, and even response content as you requested. Here's the improved version with reliability tweaks:
Bulk URL Status Checker Script
# Set TLS 1.2 for secure connections [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # Configuration - adjust these paths to match your files $inputFilePath = "C:\path\to\your\urls.txt" # Swap with your CSV path if using .csv $outputCsvPath = "C:\path\to\your\url_check_results.csv" # Initialize array to store all check results $results = @() # Read URLs based on file type if ($inputFilePath.EndsWith(".txt")) { # TXT file: one URL per line, filter out non-HTTP/HTTPS entries $urls = Get-Content -Path $inputFilePath | Where-Object { $_ -match "^https?://" } } elseif ($inputFilePath.EndsWith(".csv")) { # CSV file: assumes a column named "URL" - adjust the property name if yours differs $urls = Import-Csv -Path $inputFilePath | Select-Object -ExpandProperty URL | Where-Object { $_ -match "^https?://" } } else { Write-Error "Unsupported file type! Please use a .txt or .csv file." exit 1 } # Loop through each URL to perform checks foreach ($urlStr in $urls) { # Create a custom object to store result details $result = [PSCustomObject]@{ URL = $urlStr StatusCode = $null StatusDescription = $null ResponseContent = $null ErrorMessage = $null } try { # Set up web request $webRequest = [System.Net.WebRequest]::Create($urlStr) # Auto-follow redirects (set to $false if you want manual 3xx handling like your original script) $webRequest.AllowAutoRedirect = $true $webResponse = $webRequest.GetResponse() # Populate status details $result.StatusCode = [int]$webResponse.StatusCode $result.StatusDescription = [string]$webResponse.StatusDescription # Capture response content (your secondary request) $streamReader = New-Object System.IO.StreamReader($webResponse.GetResponseStream()) $result.ResponseContent = $streamReader.ReadToEnd() $streamReader.Close() # Clean up resources $webResponse.Close() $webResponse.Dispose() } catch { # Handle errors like connection failures or invalid URLs $result.ErrorMessage = $_.Exception.Message # Extract status code from server errors if available if ($_.Exception.Response) { $result.StatusCode = [int]$_.Exception.Response.StatusCode $result.StatusDescription = [string]$_.Exception.Response.StatusDescription } } # Add result to our collection $results += $result # Optional: Print real-time progress to console Write-Host "Checked: $urlStr | Status: $($result.StatusCode ?? 'Error')" } # Export all results to CSV $results | Export-Csv -Path $outputCsvPath -NoTypeInformation -Encoding UTF8 Write-Host "Bulk check finished! Results saved to: $outputCsvPath"
Key Improvements & Usage Notes
- Dual File Support: Works with both TXT (one URL per line) and CSV files (requires a column named
URL—adjust the script if your CSV uses a different column name likeWebsite). - Error Resilience: Uses
try/catchblocks to handle connection failures, invalid URLs, or server errors without stopping the entire bulk process. - Redirect Handling: Automatically follows redirects by default. If you want to revert to your original manual 301/302 checking logic, set
AllowAutoRedirect = $falseand add your originaldo-whileloop inside thetryblock. - Comprehensive Results: Exports URL, status code, status description, full response content, and error messages to CSV for easy analysis.
- URL Validation: Filters out lines that don't look like valid HTTP/HTTPS URLs to avoid unnecessary errors.
Quick Setup Steps
- Replace
$inputFilePathwith the path to your TXT or CSV file of URLs. - Replace
$outputCsvPathwith your desired save location for results. - Run the script in PowerShell—you'll see progress in the console, and all results will be saved to the specified CSV.
内容的提问来源于stack exchange,提问作者Rajiv Ahmed
相关产品推荐
相关产品推荐

