Windows Powershell Script for testing a list of Redirected URL's

Viewed 507

I want to a Windows PowerShell script that can test a list of URL's which are redirected. I want there status code and there target URL. I am getting for a single URL, however unable to get it for a list of URL's. If anyone can help me with the above.

1 Answers

Create a [WebRequest] object and set the AllowAutoRedirect property to $false:

# You could read this list from a file if necessary
$urls = @('http://stackoverflow.com/')

foreach($url in $urls){
  try{
    # Create WebRequest object, disallow following redirects
    $request = [System.Net.WebRequest]::Create($url)
    $request.AllowAutoRedirect = $false

    # send the request and obtain the HTTP response
    $response = $request.GetResponse()
    $statusCode = $response.StatusCode

    # Create a new output object with the needed details
    [pscustomobject]@{
      Original = $url
      Target = if($statusCode -ge 300 -and $statusCode -lt 400) {
        $response.Headers['Location']
      };
      StatusCode = +$statusCode
    }
  }
  finally {
    if($response -is [IDisposable]){
      # Dispose of the response stream (otherwise we'll be blocking the tcp socket until it times out)
      $response.Dispose()
    }
  }
}

The + in front of $statusCode ensures conversion to the numeric response code (ie 301) instead of it's name (MovedPermanently)

Related