用于测试重定向 URL 列表的 Windows Powershell 脚本 [英] Windows Powershell Script for testing a list of Redirected URL's

查看:18
本文介绍了用于测试重定向 URL 列表的 Windows Powershell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个可以测试重定向 URL 列表的 Windows PowerShell 脚本.我想要状态代码和目标 URL.我正在获取单个 URL,但无法获取 URL 列表.如果有人可以帮助我解决上述问题.

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.

推荐答案

创建一个 [WebRequest] 对象并将 AllowAutoRedirect 属性设置为 $false:

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()
    }
  }
}

$statusCode 前面的 + 确保转换为数字响应代码(即 301)而不是它的名称(永久移动)

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

这篇关于用于测试重定向 URL 列表的 Windows Powershell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆