问题
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