Reputation: 13
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!
Upvotes: 1
Views: 3554
Reputation: 28194
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;
$redirecttest.BaseResponse.responseuri.AbsoluteUri;
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.
Upvotes: 2
Reputation: 13176
Here is an example but with Internet Explorer (11). I'm not sure you can automate Firefox with PowerShell. With this example, I get a different output than the original URL.
#Instanciate IE COM Object to interact with IE
$ie = New-Object -ComObject "InternetExplorer.Application"
#store original URL
$requestUri = "http://google.com"
#open the original URL in IE
$ie.navigate($requestUri)
#while IE is busy, wait for 250 seconds and try again
while ($ie.Busy) {
Start-Sleep -Milliseconds 250
}
#retrieve the actual/final URL from the browser
$ie.Document.url
Upvotes: 0