Tuesday, October 18, 2016

Powershell Script to retrieve URL response

<#  
.SYNOPSIS  
Script to retrieve URL response & relevant details and save it in HTML file. URLs are read from file

.FILE NAME

URL-Response.ps1
#>

clear
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$urlsPath = $scriptDir + "\" + "URLs.txt"

$FileName = (Get-Date).tostring("dd-MM-yyyy-HH-mm-ss")
$file = $scriptDir + "\Logs\" + "URLs-" + $FileName +".htm"

add-type @"
    using System.Net;
    using System.Security.Cryptography.X509Certificates;
    
    public class IgnorePolicy : ICertificatePolicy {
        public IgnorePolicy() {}
        public bool CheckValidationResult(
            ServicePoint sPoint, X509Certificate cert,
            WebRequest wRequest, int certProb) {
            return true;
        }
    }
"@

$urls = Get-Content $urlsPath
$list = @()
$count = 1

foreach($url in $urls) {
    
    try{
            [System.Net.ServicePointManager]::CertificatePolicy = new-object IgnorePolicy
            $request = Invoke-WebRequest -Uri $url
            $result = Measure-Command {$request}
            $timetaken = $result.TotalMilliseconds
            $status = $request.StatusCode
            #$reslen = $request.RawContentLength

            $cusObj=New-Object -TypeName PSObject -Property @{
                TT = $timetaken
                status = $status
                #reslen = $reslen
                url = $url
                Time = Get-Date
                count = $count++
                } | Select TT,status,url,Time, count
            
            $list += $cusObj
            
         }
    
    catch {
               $_.Exception
    }
}
            $Outputreport = "<HTML><TITLE>URL Response Report</TITLE><BODY><font color =""blue"" face=""Comic Sans MS""><H2 align=left> URL Response Report </H2></font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=black align=center><TD><font color=""white"" face=""Comic Sans MS"">S.No</font></TD><TD><font color=""white"" face=""Comic Sans MS"">URL</font></TD><TD><font color=""white"" face=""Comic Sans MS"">StatusCode</font></TD><TD><font color=""white"" face=""Comic Sans MS"">Time Captured</font></TD><TD><font color=""white"" face=""Comic Sans MS"">TimeTaken(MS)</font></TD></TR>"
            foreach ($obj in $list)
            {
                if($obj.status -ne "200")
                {
                    $Outputreport += "<TR bgcolor=yellow>" 
                }
                else
                { 
                    $Outputreport += "<TR>" 
                } 
            
                $Outputreport += "<TD>$($obj.count)</TD><TD>$($obj.url)</TD><TD align=center>$($obj.status)</TD><TD align=center>$($obj.Time)</TD><TD align=center>$($obj.TT)</TD></TR>"
            }
            $Outputreport += "</Table></BODY></HTML>"
            
            $Outputreport | Out-File $file

No comments:

Post a Comment