barryokane
3/30/2017 - 9:19 AM

Powershell script to loop over a list of URLs, make a HTTP HEAD request and check for (first) 301 response.

Powershell script to loop over a list of URLs, make a HTTP HEAD request and check for (first) 301 response.

#-------------
# Script to loop over a list of URLs, make a HTTP HEAD request and check for (first) 301 response
#   INPUT: A txt file with one URL per line
#   
#   OUTPUT: A CSV file with columns for:
#               - RequestURI = the URI from than line in input file
#               - StatusCode = response status code (blank if error code!)
#               - Error = Error message (for 404 or 500 errors)
#

$linksFilePath = "C:\Temp_Stuff\{your input file}.txt"
$outCSVPath = "C:\Temp_Stuff\{your output file}.csv"

get-content $linksFilePath |
 Foreach { $uri = $_; try { Invoke-WebRequest -Uri $uri -Method HEAD -MaximumRedirection 0 -ErrorAction SilentlyContinue } catch { 
        New-Object -TypeName psobject -Property @{ Error = $_ } } } |
 Select @{Name="RequestURI";Expression={$uri}}, StatusCode, @{Name="RedirectTo";Expression={$_.Headers["Location"]}}, Error |
 Export-Csv $outCSVPath