WookieWitDaFur WookieWitDaFur - 2 months ago 34x
PowerShell Question

powershell to return and log redirected site?

Afternoon all,
Trying to create a script to go to a webpage and log if it is redirected to an expansion server. For example the site is site.school.net and under high load it is supposed to forward to site2.school.net and site3.school.net. I was looking into powershell just because I want to learn it but I am open to anything that works. I have tried

Start-Process -FilePath FireFox -ArgumentList site.school.net

and it opens a page and all that but I need to run it like every 10-15 seconds and log the url it was sent to. Any help is appreciated, thanks in advance!


Don't use a web browser for this, as it's extra overhead and makes running the script from an unattended system (like in a scheduled job) pretty difficult or impossible.

Use PowerShell's invoke-webrequest cmdlet.

$redirecttest = invoke-webrequest -uri https://jigsaw.w3.org/HTTP/300/302.html -Method get -maximumredirection 0;
Write-Output "StatusCode: $($redirecttest.statuscode)";
Write-Output "Redirecting to: $($redirecttest.headers.location)";

This will attempt to reach the page at the specified URL and not follow a redirect if one is given. It then captures the HTTP headers and outputs the HTTP status code (302, moved permanently in this case) and the location that we're being redirected to.

It will also spit out an error because the server has instructed the client to redirect more times than the client has been told to redirect. handle that error however you prefer/need.

You can then test the redirect location that you're sent to validate that the redirect is working properly:

if ($Redirecttest.headers.location -eq "http://site2.school.net" -or $Redirecttest.headers.location -eq "http://site3.school.net") {
Write-output "Success";
} else {
Write-output "Redirect broken";

Or, you could just invoke the web request and allow the redirection, and inspect the resulting URL.

$redirecttest = invoke-webrequest -uri https://jigsaw.w3.org/HTTP/300/302.html -Method get;

Note that this will only work if the HTTP server sends true HTTP 30X status codes, as opposed to depending upon a client-side redirect via a META tag or JavaScript.