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

醉酒当歌 提交于 2021-01-28 22:13:07

问题


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:


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)



来源:https://stackoverflow.com/questions/60547691/windows-powershell-script-for-testing-a-list-of-redirected-urls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!