Public/Get-UrlStatusCode.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
function Get-UrlStatusCode {
    # Stems from issue #24 (https://github.com/repasscloud/software-library/issues/24)
    # Returns the Status Code of a web URL that is passed in as an arg
    # Should always return a 200 result to be successful
    # List of URL status codes can be found here: https://www.w3.org/Protocols/HTTP/HTRESP.html
    #
    # Usage:
    #
    # $query = Get-URLStatusCode -Url https://www.google.com/
    # $query -eq 200
    #
    # Source: https://stackoverflow.com/a/20262872
        
    param(
        [Parameter(Mandatory=$true,
            ValueFromPipeline=$true,
            ValueFromPipelineByPropertyName=$true,
            ValueFromRemainingArguments=$false,
            HelpMessage='Provide URL to return HTTP Status Code.',
            Position=0)]
        [Alias('uri')]
        [Uri]$Url
    )
    
    begin {
        # Set TLS 1.2
        [Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12
    }

    process {
        # First we create the request.
        $HTTP_Request = [System.Net.WebRequest]::Create($Url)
        
        # We then get a response from the site.
        $HTTP_Response = $HTTP_Request.GetResponse()
        
        # We then get the HTTP code as an integer.
        $HTTP_Status = [int]$HTTP_Response.StatusCode
        
        return $HTTP_Status
    
        # Finally, we clean up the http request by closing it.
        if ($null -eq $HTTP_Response) {
        }
        else {
            $HTTP_Response.Close()
        }
    }
    end {
        # Clean up memory
        [System.GC]::Collect()
    }
}