Public/WebConnection.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<#
.SYNOPSIS
Tests to see if a Uri by Invoke-WebRequest -Method Head
 
.DESCRIPTION
Tests to see if a Uri by Invoke-WebRequest -Method Head
 
.PARAMETER Uri
Uri to test
 
.LINK
https://osd.osdeploy.com/module/functions/webconnection
 
.NOTES
21.3.12 Renamed from Invoke-UrlExpression
 
#>

function Test-WebConnection {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $True)]
        [string]$Uri = 'google.com'
    )
    
    begin {}
    
    process {
        $Params = @{
            Method = 'Head'
            Uri = $Uri
            UseBasicParsing = $True
        }

        try {
            Write-Verbose "Test-WebConnection OK: $Uri"
            Invoke-WebRequest @Params | Out-Null
            $true
        }
        catch {
            Write-Verbose "Test-WebConnection FAIL: $Uri"
            $false
        }
        finally {
            $Error.Clear()
        }
    }
    
    end {}
}
function Wait-WebConnection {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $True)]
        [string]$Uri = 'powershellgallery.com'
    )


    if ((Test-WebConnection -Uri 'powershellgallery.com') -eq $true) {
        Write-Verbose "Wait-WebConnection to $Uri"
    }
    else {
        do {
            Write-Verbose "Wait-WebConnection to $Uri"
            
            Write-Verbose "Waiting 10 seconds to try again ..."
            Start-Sleep -Seconds 10
    
        } until ((Test-WebConnection -Uri 'powershellgallery.com') -eq $true)
    }
    $Error.Clear()
}