AzStackHciConnectivity/AzStackHci.Connectivity.Helpers.psm1

class AzStackHciConnectivityTarget
{
    # Attributes for Azure Monitor schema
    [string]$Name #Name of the individual test/rule/alert that was executed. Unique, not exposed to the customer.
    [string]$Title #User-facing name; one or more sentences indicating the direct issue.
    [string]$Severity #Severity of the result (Critical, Warning, Informational, Hidden) – this answers how important the result is. Critical is the only update-blocking severity.
    [string]$Description #Detailed overview of the issue and what impact the issue has on the stamp.
    [psobject]$Tags #Key-value pairs that allow grouping/filtering individual tests. For example, "Group": "ReadinessChecks", "UpdateType": "ClusterAware"
    [string]$Status #The status of the check running (i.e. Failed, Succeeded, In Progress) – this answers whether the check ran, and passed or failed.
    [string]$Remediation #Set of steps that can be taken to resolve the issue found.
    [string]$TargetResourceID #The unique identifier for the affected resource (such as a node or drive).
    [string]$TargetResourceName #The name of the affected resource.
    [string]$TargetResourceType #The type of resource being referred to (well-known set of nouns in infrastructure, aligning with Monitoring).
    [datetime]$Timestamp #The Time in which the HealthCheck was called.
    [psobject[]]$AdditionalData #Property bag of key value pairs for additional information.
    [string]$HealthCheckSource #The name of the services called for the HealthCheck (I.E. Test-AzureStack, Test-Cluster).

    # Attribute for performing check
    [string[]]$EndPoint
    [string[]]$Protocol

    # Additional Attributes for end user interaction
    [string[]]$Service # short cut property to Service from tags
    [string[]]$OperationType # short cut property to Operation Type from tags
    [string[]]$Group # short cut property to group from tags
    [bool]$Mandatory # short cut property to mandatory from tags
    [bool]$System # targets for system checks such as proxy traversal
}

class AzStackHciConnectivityManifest
{
    [string]$Title
    [System.Version]$Version
    [PsObject[]]$Targets
}

Import-LocalizedData -BindingVariable lcTxt -FileName AzStackHci.Connectivity.Strings.psd1

function Test-Dns
{
    <#
    .SYNOPSIS
        Test DNS Resolution
    #>

    [CmdletBinding()]
    param (
        [System.Management.Automation.Runspaces.PSSession]
        $PsSession
    )

    # scriptblock to test dns resolution for each dns server
    $testDnsSb = {

        # Pass in localized strings
        $NoDnsConfigured = $args[0]
        $QueryDnsFail = $args[1]
        $QueryDnsPass = $args[2]
        $SkipDnsWithProxy = $args[3]
        # Test if proxy is enabled and return because proxy maybe doing dns resolution
        function IsProxyEnabled
        {
            $line1, $line2, $line3, $JsonLines = netsh winhttp show advproxy
            $proxy = $JsonLines | ConvertFrom-Json
            [bool]$proxy.Proxy
        }

        if (IsProxyEnabled)
        {
            return @{
                Resource  = $SkipDnsWithProxy
                Status    = 'SUCCESS'
                TimeStamp = [datetime]::UtcNow
                Source    = $ENV:COMPUTERNAME
                Detail    = $SkipDnsWithProxy -f $ENV:COMPUTERNAME
            }
        }

        $AdditionalData = @()

        # Get local DNS servers
        $dnsServers = @()
        $netAdapter = Get-NetAdapter | Where-Object Status -EQ Up
        $dnsServer = Get-DnsClientServerAddress -InterfaceIndex $netAdapter.ifIndex -AddressFamily IPv4
        $dnsServers += $dnsServer | ForEach-Object { $PSITEM.Address } | Sort-Object | Get-Unique

        if (-not $dnsServers)
        {
            return @{
                Resource  = $NoDnsConfigured
                Status    = 'FAILURE'
                TimeStamp = [datetime]::UtcNow
                Source    = $ENV:COMPUTERNAME
                Detail    = $NoDnsConfigured
            }
        }
        else
        {
            foreach ($dnsServer in $dnsServers)
            {
                $dnsResult = $false
                $dnsResult = Resolve-DnsName -Name microsoft.com -Server $dnsServer -DnsOnly -ErrorAction SilentlyContinue -QuickTimeout -Type A
                if ([int]($dnsResult.count) -eq 0)
                {
                    $detail = $QueryDnsFail -f $dnsServer, 'microsoft.com', $ENV:COMPUTERNAME, [int]($dnsResult.count)
                }
                else
                {
                    $detail = $QueryDnsPass -f $dnsServer, 'microsoft.com', $ENV:COMPUTERNAME, [int]($dnsResult.count), ($dnsResult.IpAddress -join ',')
                }

                if ($dnsResult)
                {
                    if ($dnsResult[0] -is [Microsoft.DnsClient.Commands.DnsRecord])
                    {
                        $status = 'SUCCESS'
                    }
                    else
                    {
                        $status = 'FAILURE'
                    }
                }
                else
                {
                    $status = 'FAILURE'
                }
                $AdditionalData += @{
                    Resource  = $dnsServer
                    Status    = $status
                    TimeStamp = [datetime]::UtcNow
                    Source    = $ENV:COMPUTERNAME
                    Detail    = $detail
                }
            }
        }
        $AdditionalData
    }

    # run scriptblock
    $dnsargs = @{
        ArgumentList = $lcTxt.NoDnsConfigured, $lcTxt.QueryDnsFail, $lcTxt.QueryDnsPass, $lcTxt.SkipDnsWithProxy
    }
    $testDnsServer = if ($PsSession)
    {
        Invoke-Command -Session $PsSession -ScriptBlock $testDnsSb @dnsArgs
    }
    else
    {
        Invoke-Command -ScriptBlock $testDnsSb @dnsArgs
    }

    # build result
    $now = [datetime]::UtcNow

    # Write result to verbose log
    $testDnsServer | Foreach-Object {
        Log-Info $_.Detail -Type $(if ( $_.Status -eq 'FAILURE' ){ "WARNING" } else { "INFORMATIONAL" } )
    }

    $testDnsResult += $testDnsServer | Foreach-Object {
        $params = @{
            Name               = 'AzStackHci_Connectivity_Test_Dns'
            Title              = 'Test DNS'
            DisplayName        = 'Test DNS'
            Severity           = 'Critical'
            Description        = 'Test DNS Resolution'
            Tags               = @{}
                #Service = 'System'
            #}
            Remediation        = 'https://learn.microsoft.com/en-us/azure-stack/hci/deploy/deployment-tool-checklist'
            TargetResourceID   = "$($PsItem.Source)/$($PsItem.Resource)"
            TargetResourceName = $PsItem.Resource
            TargetResourceType = 'DNS'
            Timestamp          = $now
            Status             = $PsItem.Status
            AdditionalData     = $PsItem
            HealthCheckSource  = $ENV:EnvChkrId
        }
        New-AzStackHciResultObject @params
    }
    return $testDnsResult
}

function Get-AzStackHciConnectivityServiceName
{
    <#
    .SYNOPSIS
        Retrieve Services from built target packs
    .DESCRIPTION
        Retrieve Services from built target packs
    .EXAMPLE
        PS C:\> Get-AzStackHciServices
        Explanation of what the example does
    .INPUTS
        Service
    .OUTPUTS
        PSObject
    .NOTES
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [string[]]
        $Service,

        [Parameter(Mandatory = $false)]
        [switch]
        $IncludeSystem
    )
    try
    {
        Get-AzStackHciConnectivityTarget -IncludeSystem:$IncludeSystem | Select-Object -ExpandProperty Service | Sort-Object | Get-Unique
    }
    catch
    {
        throw "Failed to get services names. Error: $($_.Exception.Message)"
    }
}

function Get-AzStackHciConnectivityOperationName
{
    <#
    .SYNOPSIS
        Retrieve Operation Types from built target packs
    .DESCRIPTION
        Retrieve Operation Types from built target packs e.g. Deployment, Update, Secret Rotation.
    .EXAMPLE
        PS C:\> Get-AzStackHciConnectivityOperationName
        Explanation of what the example does
    .INPUTS
        Service
    .OUTPUTS
        PSObject
    .NOTES
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false)]
        [string]
        $OperationType
    )
    try
    {
        Get-AzStackHciConnectivityTarget | Select-Object -ExpandProperty OperationType | Sort-Object | Get-Unique
    }
    catch
    {
        throw "Failed to get services names. Error: $($_.Exception.Message)"
    }
}

function Get-AzStackHciConnectivityTarget
{
    <#
        .SYNOPSIS
            Retrieve Endpoints from built target packs
        .DESCRIPTION
            Retrieve Endpoints from built target packs
        .EXAMPLE
            PS> Get-AzStackHciConnectivityTarget
            Get all connectivity targets
        .EXAMPLE
            Get-AzStackHciConnectivityTarget -Service ARC | ft Name, Title, Service, OperationType -AutoSize
            Get all ARC connectivity targets
        .EXAMPLE
            PS> Get-AzStackHciConnectivityTarget -Service ARC -OperationType Workload | ft Name, Title, Service, OperationType -AutoSize
            Get all ARC targets for workloads
        .EXAMPLE
            PS> Get-AzStackHciConnectivityTarget -OperationType Workload | ft Name, Title, Service, OperationType -AutoSize
            Get all targets for workloads
        .EXAMPLE
            PS> Get-AzStackHciConnectivityTarget -OperationType ARC -OperationType Update -Additive | ft Name, Title, Service, OperationType -AutoSize
            Get all ARC targets and all targets for Update
        .INPUTS
            Service - String array
            OperationType - String array
            Additive - Switch
        .OUTPUTS
            PSObject
        .NOTES
    #>

    [CmdletBinding()]
    param (

        [Parameter(Mandatory = $false)]
        [string[]]
        $Service,

        [Parameter(Mandatory = $false)]
        [string[]]
        $OperationType,

        [Parameter(Mandatory = $false)]
        [switch]
        $Additive,

        [Parameter(Mandatory = $false)]
        [switch]
        $IncludeSystem,

        [Parameter(Mandatory = $false)]
        [switch]
        $LocalOnly

    )
    try
    {
        Import-AzStackHciConnectivityTarget -LocalOnly:$LocalOnly
        $executionTargets = @()
        # Additive allows the user to "-OR" their parameter values
        if ($Additive)
        {
            Write-Verbose -Message "Getting targets additively"
            if (-not [string]::IsNullOrEmpty($Service))
            {
                Write-Verbose -Message ("Getting targets by Service: {0}" -f ($Service -join ','))
                foreach ($svc in $Service)
                {
                    $executionTargets += $Script:AzStackHciConnectivityTargets | Where-Object { $svc -in $_.Service }
                }
            }
            if (-not [string]::IsNullOrEmpty($OperationType))
            {
                Write-Verbose -Message ("Getting targets by Operation Type: {0}" -f ($OperationType -join ','))
                foreach ($Op in $OperationType)
                {
                    $executionTargets += $Script:AzStackHciConnectivityTargets | Where-Object { $Op -in $_.OperationType }
                }
            }
            if ([string]::IsNullOrEmpty($OperationType) -and [string]::IsNullOrEmpty($Service))
            {
                $executionTargets += $Script:AzStackHciConnectivityTargets
            }
        }
        else
        {
            if ([string]::IsNullOrEmpty($OperationType) -and [string]::IsNullOrEmpty($Service))
            {
                $executionTargets += $Script:AzStackHciConnectivityTargets
            }
            elseif (-not [string]::IsNullOrEmpty($Service) -and [string]::IsNullOrEmpty($OperationType))
            {
                Write-Verbose -Message ("Getting targets by Service: {0}" -f ($Service -join ','))
                foreach ($svc in $Service)
                {
                    $executionTargets += $Script:AzStackHciConnectivityTargets | Where-Object { $svc -in $_.Service }
                }
            }
            elseif (-not [string]::IsNullOrEmpty($OperationType) -and [string]::IsNullOrEmpty($Service))
            {
                Write-Verbose -Message ("Getting targets by Operation Type: {0}" -f ($OperationType -join ','))
                foreach ($Op in $OperationType)
                {
                    $executionTargets += $Script:AzStackHciConnectivityTargets | Where-Object { $Op -in $_.OperationType }
                }
            }
            else
            {
                Write-Verbose -Message ("Getting targets by Operation Type: {0} and Service: {1}" -f ($OperationType -join ','), ($Service -join ','))
                $executionTargetsByOp = @()
                foreach ($Op in $OperationType)
                {
                    $executionTargetsByOp += $Script:AzStackHciConnectivityTargets | Where-Object { $Op -in $_.OperationType }
                }
                foreach ($svc in $Service)
                {
                    $executionTargets += $executionTargetsByOp | Where-Object { $svc -in $_.Service }
                }
            }
        }

        # Always add Mandatory targets
        $executionTargets += $Script:AzStackHciConnectivityTargets | Where-Object Mandatory | ForEach-Object {
            if ($PSITEM -notin $executionTargets)
            {
                $PSITEM
            }
        }

        if ($IncludeSystem)
        {
            return $executionTargets
        }
        else
        {
            return ($executionTargets | Where-Object Service -NotContains 'System')
        }
    }
    catch
    {
        throw "Get failed: $($_.exception)"
    }
}

function Import-AzStackHciConnectivityTarget
{
    <#
    .SYNOPSIS
        Retrieve Endpoints from built target packs
    .DESCRIPTION
        Retrieve Endpoints from built target packs
    .EXAMPLE
        PS C:\> Import-AzStackHciConnectivityTarget
        Explanation of what the example does
    .INPUTS
        URI
    .OUTPUTS
        PSObject
    .NOTES
    #>

    [CmdletBinding()]
    param (
        [switch]
        $LocalOnly
    )
    try
    {
        $Script:AzStackHciConnectivityTargets = @()
        if (-not $LocalOnly)
        {
            $Script:AzStackHciConnectivityTargets += Get-CloudEndpointFromManifest
        }

        if ($Script:AzStackHciConnectivityTargets) {
            return
        }
        else
        {
            $targetFiles = Get-ChildItem -Path "$PSScriptRoot\Targets\*.json" | Select-Object -ExpandProperty FullName
            Write-Verbose ("Importing {0}" -f ($targetFiles -join ','))
            ForEach ($targetFile in $targetFiles)
            {
                try
                {
                    # TO DO - Add validations:
                    # - protocol should not contain ://
                    $targetPackContent = Get-Content -Path $targetFile | ConvertFrom-Json -WarningAction SilentlyContinue
                    foreach ($target in $targetPackContent)
                    {
                        #Set Name of the individual test/rule/alert that was executed. Unique, not exposed to the customer.
                        $target | Add-Member -MemberType NoteProperty -Name HealthCheckSource -Value $ENV:EnvChkrId
                        $target.TargetResourceID = $target.EndPoint -join '_'
                        $target.TargetResourceName = $target.EndPoint -join '_'
                        $target.TargetResourceType = 'External Endpoint'
                        $Script:AzStackHciConnectivityTargets += [AzStackHciConnectivityTarget]$target
                    }
                }
                catch
                {
                    throw ("Unable to read {0}. Error: {1}" -f (Split-Path -Path $targetFile -Leaf), $_.Exception.Message)
                }
            }
        }
    }
    catch
    {
        throw "Import failed: $($_.exception)"
    }
}

function Get-SigningRootChain
{
    <#
    .SYNOPSIS
        Get signing root for https endpoint
    .DESCRIPTION
        Get signing root for https endpoint
    .EXAMPLE
        PS C:\> Get-SigningRoot -uri MicrosoftOnline.com
        Explanation of what the example does
    .INPUTS
        URI
    .OUTPUTS
        Output (if any)
    .NOTES
    #>

    [CmdletBinding()]
    param (
        [Parameter()]
        [System.Uri]
        $Uri,

        [Parameter()]
        [System.Management.Automation.Runspaces.PSSession]
        $PsSession,

        [Parameter()]
        [string]
        $Proxy,

        [Parameter()]
        [pscredential]
        $proxyCredential
    )
    try
    {
        $sb = {
            $uri = $args[0]
            $proxy = $args[1]
            $proxyCredential = $args[2]
            $GetSslCertChainFunction = $args[3]

            if (-not (Get-Command -Name Get-SslCertificateChain -ErrorAction SilentlyContinue))
            {
                throw "Cannot find Get-SslCertificateChain in AzStackHci.EnvironmentChecker.PortableUtilities module"
            }
            else
            {
                Write-Verbose "Found Get-SslCertificateChain in AzStackHci.EnvironmentChecker.Utilities module"
                $chain = Get-SslCertificateChain -Url $Uri -Proxy $Proxy -ProxyCredential $ProxyCredential
            }
            return $chain.ChainElements.Certificate
        }
        $ChainElements = if ($PsSession)
        {
            Invoke-Command -Session $PsSession -ScriptBlock $sb -ArgumentList $Uri, $Proxy, $ProxyCredential,${function:Get-SslCertificateChain}
        }
        else
        {
            Invoke-Command -ScriptBlock $sb -ArgumentList $Uri, $Proxy, $ProxyCredential,${function:Get-SslCertificateChain}
        }
        return $ChainElements
    }
    catch
    {
        throw $_
    }
}

function Test-RootCA
{
    <#
    .SYNOPSIS
        Short description
    .DESCRIPTION
        Long description
    .EXAMPLE
        PS C:\> <example usage>
        Explanation of what the example does
    .INPUTS
        Inputs (if any)
    .OUTPUTS
        Output (if any)
    .NOTES
        General notes
    #>

    [CmdletBinding()]
    param(
        [Parameter()]
        [System.Management.Automation.Runspaces.PSSession]
        $PsSession,

        [Parameter()]
        [string]
        $Proxy,

        [Parameter()]
        [pscredential]
        $ProxyCredential
    )
    try
    {
        if ($Script:AzStackHciConnectivityTargets)
        {
            $rootCATarget = $Script:AzStackHciConnectivityTargets | Where-Object Name -EQ System_Check_SSL_Inspection_Detection
            if ($rootCATarget.count -ne 1)
            {
                throw "Expected 1 System_RootCA, found $($rootCATarget.count)"
            }
            Install-UtilityModule -PsSession $PsSession -CmdletName Get-SslCertificateChain
            # We have two endpoints to check, they expire 6 months apart
            # meaning we should get a warning if criteria needs to change
            # 1 only require 1 endpoint to not be re-encrypted to succeed.
            $rootCATargetUrls = @()
            $rootCATarget.EndPoint | Foreach-Object {
                foreach ($p in $rootCATarget.Protocol) {
                    $rootCATargetUrls += "{0}://{1}" -f $p,$PSITEM
                }
            }

            $AdditionalData = @()

            foreach ($rootCATargetUrl in $rootCATargetUrls) {
                Log-Info "Testing SSL chain for $rootCATargetUrl"
                [array]$ChainElements = Get-SigningRootChain -Uri $rootCATargetUrl -PsSession $PsSession -Proxy $Proxy -ProxyCredential $ProxyCredential
                # This is our canary internet endpoint, if we can't get the chain we probably don't have internet access.
                if ($null -eq $ChainElements)
                {
                    $Status = 'FAILURE'
                    $detail = "Failed to get certificate chain for $rootCATargetUrl. Ensure the endpoint is accessible and proxy configuration is correct."
                    Log-Info $detail -Type Warning
                }
                else
                {
                    # Remove the leaf as this will always contain O=Microsoft in its subject
                    $ChainElements = $ChainElements[1..($ChainElements.Length-1)]
                    $subjectMatchCount = 0
                    # We check for 2 expected subjects and only require 1 to succeed
                    $rootCATarget.Tags.ExpectedSubject | Foreach-Object {
                        if ($ChainElements.Subject -match $PSITEM)
                        {
                            $subjectMatchCount++
                        }
                    }
                    if ($subjectMatchCount -ge 1)
                    {
                        $Status = 'SUCCESS'
                        $detail = "Expected at least 1 chain certificate subject to match $($rootCATarget.Tags.ExpectedSubject -join ' or '). $subjectMatchCount matched."
                        Log-Info $detail
                    }
                    else
                    {
                        $Status = 'FAILURE'
                        $detail = "Expected at least 1 chain certificate subjects to match $($rootCATarget.Tags.ExpectedSubject -join ' or '). $subjectMatchCount matched. Actual subjects $($ChainElements.Subject -join ','). SSL decryption and re-encryption detected."
                        Log-Info $detail -Type Error
                    }
                }
                $AdditionalData += @{
                    Source    = if ([string]::IsNullOrEmpty($PsSession.ComputerName)) { $ENV:COMPUTERNAME } else { $PsSession.ComputerName }
                    Resource  = $rootCATargetUrl
                    Status    = $Status
                    Detail    = $detail
                    TimeStamp = [datetime]::UtcNow
                }
            }

            $result = @()
            $result += $AdditionalData | ForEach-Object {
                $params = @{
                    Name               = $rootCATarget.Name
                    Title              = $rootCATarget.Title
                    DisplayName        = $rootCATarget.Title
                    Severity           = $rootCATarget.Severity
                    Description        = $rootCATarget.Description
                    Tags               = @{
                        Service = 'System'
                        Mandatory = $true
                    }
                    Remediation        = 'https://learn.microsoft.com/en-us/azure-stack/hci/deploy/deployment-tool-checklist'
                    TargetResourceID   = "$($PsItem.Source)/$($PsItem.Resource)"
                    TargetResourceName = $PsItem.Resource
                    TargetResourceType = $rootCATarget.TargetResourceType
                    Timestamp          = $PsItem.TimeStamp
                    Status             = $PsItem.Status
                    AdditionalData     = $PsItem
                    HealthCheckSource  = $ENV:EnvChkrId
                }
                New-AzStackHciResultObject @params
            }
            Remove-UtilityModule -PsSession $PsSession
            return $result
        }
        else
        {
            throw "No AzStackHciConnectivityTargets"
        }
    }
    catch
    {
        Log-Info "Test-RootCA failed with error: $($_.exception.message)" -Type Warning
    }
}

function Get-UniqueEndpoint
{
    [CmdletBinding()]
    param (
        [Parameter()]
        [PsObject]
        $Target
    )
    # Build list of unique endpoints
    $uriList = @()
    foreach ($t in $Target)
    {
        foreach ($u in $t.EndPoint)
        {
            foreach ($p in $t.Protocol)
            {
                $uriList += "{0}://{1}" -f $p, ($u -Replace '\*', 'www')
            }
        }
    }
    Log-Info "Uri Count (total): $($uriList.count)"
    $uriList = $uriList | Sort-Object -Unique
    Log-Info "Uri Count (Unique): $($uriList.count)"
    return $uriList
}

function Invoke-WebRequestEx
{
    <#
    .SYNOPSIS
        Get Connectivity via Invoke-WebRequest
    .DESCRIPTION
        Get Connectivity via Invoke-WebRequest, supporting proxy.
        This function takes a connectivity target definition, creates a PS(5) Job for each endpoint and protocol and returns the results.
        If PsSession is provided, the jobs are run on the remote machine.
        Success is defined as a 200 status code or a valid status code (not service available),
        with a GET method and the response Uri is the same as the request Uri.
    .EXAMPLE
        PS C:\> Invoke-WebRequestEx -Target $Target
        Explanation of what the example does
    .INPUTS
        URI
    .OUTPUTS
        Output (if any)
    .NOTES
        In the case of a proxy being provided, the proxy is used for all endpoints.
        In the case of a proxy being configured on the box, invoke-webrequest will use the wininet proxy for all calls.
        Certificate Validation is disabled for the calls.
    #>

    [CmdletBinding()]
    param (
        [Parameter()]
        [psobject[]]
        $Target,

        [Parameter()]
        [System.Management.Automation.Runspaces.PSSession[]]
        $PsSession,

        [Parameter()]
        [string]
        $Proxy,

        [Parameter()]
        [pscredential]
        $ProxyCredential

    )

    $Target | Add-Member -MemberType NoteProperty -Name TimeStamp -Value [datetime]::UtcNow -Force
    $ScriptBlock = {
        $Uri = $args[0]
        $TimeoutSecs = $args[1]
        $maxJobs = $args[2]
        $Proxy = $args[3]
        $ProxyCredential = $args[4]

        $timeoutSecondsDefault = 10
        if ([string]::IsNullOrEmpty($TimeoutSecs))
        {
            $timeout = $timeoutSecondsDefault
        }
        else
        {
            $timeout = $TimeoutSecs
        }
        # Create an array of jobs for all uris and protocols
        $inProgressJobList = @()
        $totalJobList = @()
        $results = @()
        foreach ($u in $uri)
        {
            $iwrScriptBlock = {
                $retry = 0
                $maxRetry = 3
                do {
                    $retry++
                    if ($retry -gt 1)
                    {
                        Start-Sleep -Seconds 5
                    }

                    try
                    {
                        $uri = $args[0]
                        $proxy = $args[1]
                        $proxyCred = $args[2]
                        $Timeout = $args[3]
                        $iwrParams =@{
                            Uri = $Uri
                            UseBasicParsing = $true
                            TimeoutSec = 30
                        }

                        # Ignore certificate validation and use TLS 1.2
                        if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
                        {
                            $certCallback = @"
                            using System;
                            using System.Net;
                            using System.Net.Security;
                            using System.Security.Cryptography.X509Certificates;
                            public class ServerCertificateValidationCallback
                            {
                                public static void Ignore()
                                {
                                    if(ServicePointManager.ServerCertificateValidationCallback == null)
                                    {
                                        ServicePointManager.ServerCertificateValidationCallback +=
                                            delegate
                                            (
                                                Object obj,
                                                X509Certificate certificate,
                                                X509Chain chain,
                                                SslPolicyErrors errors
                                            )
                                            {
                                                return true;
                                            };
                                    }
                                }
                            }
"@

                            $null = Add-Type $certCallback
                            $null = [ServerCertificateValidationCallback]::Ignore()
                            $null = [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
                        }

                        if ($proxy) {
                            $iwrParams.Add('Proxy', $proxy)
                            $iwrParams.Add('ProxyUseDefaultCredentials', $true)
                        }

                        if ($proxyCred) {
                            $iwrParams.Remove('ProxyUseDefaultCredentials')
                            $iwrParams.Add('ProxyCredential', $proxyCred)
                        }
                        $stopwatch = [System.Diagnostics.Stopwatch]::new()
                        $Stopwatch.Start()
                        $webOut = Invoke-WebRequest @iwrParams
                        $Stopwatch.Stop()
                        $statusCode = $webout.StatusCode
                        $webResponse = $webOut.BaseResponse
                        $headers = $webOut.Headers
                        $content = $webOut.Content
                    }
                    catch {
                        if ($stopwatch.IsRunning)
                        {
                            $stopwatch.Stop()
                        }
                        $webResponse = $_.Exception.Response

                        if ($webResponse) {
                            try {
                                $statusCode = [int]$webResponse.StatusCode
                                $headers = @{}
                                $content = [System.Text.Encoding]::UTF8.GetString($webResponse.GetResponseStream().ToArray())
                                foreach ($header in $webResponse.Headers) {
                                    $headers.$header = $webResponse.GetResponseHeader($header)
                                }
                                if ($webResponse.ContentType -eq 'application/json') {
                                    $content = ConvertFrom-Json -InputObject $content
                                }
                            }
                            catch {}
                        }
                        $exception = @{ExceptionMessage = $_.Exception.Message; ErrorDetails = $_.ErrorDetails.Message; NonHTTPFailure = [System.String]::IsNullOrEmpty($webResponse) }
                    }

                    # Response Analysis
                    # if status code is 200 return true
                    # otherwise if the status code is a HTTP status code and the response Uri is the same as the request Uri and the method is GET, return true
                    $isHttpStatusCode = $webResponse.StatusCode -is [System.Net.HttpStatusCode]
                    $responseUriMatch = ([system.uri]$webResponse.ResponseUri).Host -eq ([system.uri]$uri).Host
                    $responseMethodIsGet = $webResponse.Method -eq 'GET'
                    $serviceUnavailable = $webResponse.StatusCode -eq [System.Net.HttpStatusCode]::ServiceUnavailable
                    $test = $webResponse.StatusCode -eq [System.Net.HttpStatusCode]::OK -or ($isHttpStatusCode -and $responseUriMatch -and $responseMethodIsGet -and !$serviceUnavailable)
                    # Gather TCP net connection to test connectivity if it failed.
                    if (-not $test)
                    {
                        $tnc = Test-NetConnection -ComputerName ([system.uri]$uri).Host -Port ([system.uri]$uri).Port -InformationLevel Quiet -WarningAction SilentlyContinue
                    }

                    $Detail = "TestIsSuccess: $test`r`nStatusCode: $statusCode`r`nResponseUri: $($webResponse.ResponseUri)`r`nResponseUriMatch: $responseUriMatch`r`nResponseMethodIsGet: $responseMethodIsGet`r`nTCPNetConnection: $tnc`r`nserviceUnavailable: $serviceUnavailable"
                } while ($test -eq $false -and $retry -lt $maxRetry)
                return @{
                    Source              = $env:ComputerName
                    Retry               = "$retry / $maxRetry"
                    LatencyInMs         = $stopwatch.ElapsedMilliseconds
                    ExceptionMessage    = $Exception.ExceptionMessage
                    Resource            = $Uri
                    Protocol            = $p
                    Status              = if ($test) { "SUCCESS" } else { "FAILURE" }
                    TimeStamp           = [datetime]::UtcNow
                    StatusCode          = $StatusCode
                    Detail              = $Detail
                    DebugDtls           = @{
                        'Test' = $test
                        'Retries' = "$retry / $maxRetry"
                        'Uri' = $Uri
                        'StatusCode'= $statusCode
                        'TCPNetConnection' = $tnc
                        'WebResponse' = $webResponse
                        'Headers' = $headers
                        'Exception' = $exception
                        'serviceUnavailable' = $serviceUnavailable
                        'ResponseUriMatch' = $responseUriMatch
                        'ResponseMethodIsGet' = $responseMethodIsGet
                        'ResponseUri' = $webResponse.ResponseUri
                        'ExceptionMessage' = $Exception.ExceptionMessage
                        'ErrorDetails' = $Exception.ErrorDetails
                        'NonHTTPFailure' = $Exception.NonHTTPFailure
                        'Server' = $webResponse.Server
                        'PowerShellVersion' = $PSVersionTable.PSVersion.Major
                        'LatencyInMs' = $stopwatch.ElapsedMilliseconds
                    }
                }
            }

            # Start job for a url
            # add job to inProgressJobList and totalJobList
            # check inProgressJobList is greater or equal than maxJobs
            # if so wait for any job to finish before adding more
            $job = Start-Job -PSVersion 5.1 -ArgumentList $u, $proxy, $proxyCred, $timeout -ScriptBlock $iwrScriptBlock
            $inProgressJobList += $job
            $totalJobList += $job.id
            if ($inProgressJobList.Count -ge $maxJobs) {
                $finishedJob = @()
                $finishedJob = $inProgressJobList | Wait-Job -Any
                if ($finishedJob) {
                    $inProgressJobList = $inProgressJobList | Where-Object { $_ -ne $finishedJob }
                }
            }
        }
        Wait-Job -Id $totalJobList | Out-Null
        $results += Receive-Job -Id $totalJobList
        Remove-Job -Id $totalJobList
        return $results
    }
    # Set max concurrent jobs
    if ($ENV:EnvChkrId -like 'PreUpdate*')
    {
        $maxJobs = 3
    }
    else
    {
        $maxJobs = 10
    }
    # Create a copy of the Target object
    $result = $Target | Select-Object -Property *
    $UriList = Get-UniqueEndpoint -Target $Target
    $sessionArgs = @()
    if ($result)
    {
        $sessionArgs += @($uriList,$result.Tags.TimeoutSecs, $maxJobs)
    }
    if ($Proxy)
    {
        $sessionArgs += $Proxy
    }
    if ($ProxyCredential)
    {
        $sessionArgs += $ProxyCredential
    }
    # Run Invoke-WebRequests on remote machines if PsSession is provided
    $AdditionalDataResults = @()
    $AdditionalDataResults += if ($PsSession)
    {
        Log-Info "Sending requests to $($PsSession.ComputerName -join ',') to test $($UriList.Count) URIs, this may take a while."
        Invoke-Command -Session $PsSession -ScriptBlock $ScriptBlock -ArgumentList $sessionArgs
        Log-Info "Received responses from $($PsSession.ComputerName -join ',')."
    }
    else
    {
        Log-Info "Sending requests to $ENV:COMPUTERNAME to test $($UriList.Count) URIs, this may take a while."
        Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $sessionArgs
        Log-Info "Received responses from $ENV:COMPUTERNAME."
    }
    $finalResult = Update-TargetWithResult -Target $Target -AdditionalDataResults $AdditionalDataResults
    return $finalResult
}

function Log-EndPointResult
{
    [CmdletBinding()]
    param (
        [Parameter()]
        [psobject]
        $Result,

        [string]
        $Name,

        [string]
        $Severity
    )
    # In the case of failures, log the debug info to aid troubleshooting
    if ( $Result.Status -eq 'FAILURE' ){
        Log-Info ("{0}: {1} {2} ({3})" -f $Result.Status, $Result.Source, $Result.Resource, $result.ExceptionMessage) -Type $Severity -Function 'Invoke-WebrequestEx'
        Log-Info ("Debug {0}: {1} {2}" -f $Result.Source, $Result.Resource, ($Result.DebugDtls | ConvertTo-Json)) -Type $Severity -Function 'Invoke-WebrequestEx'
    }
    else {
        Log-Info ("{0}: {1} {2} ({3}ms)" -f $Result.Status, $Result.Source, $Result.Resource, $result.LatencyInMs) -Function 'Invoke-WebrequestEx'
    }
}

function Update-TargetWithResult
{
    [CmdletBinding()]
    param (
        [Parameter()]
        [PsObject[]]
        $Target,

        [Parameter()]
        [PsObject[]]
        $AdditionalDataResults
    )
    # Match the test result to all the target that match the endpoint
    $result = $Target | Select-Object -Property *
    $finalResult = @()

    # Inspect each result
    foreach ($dataResult in $AdditionalDataResults)
    {
        # find the target that matches the endpoint
        $matchingResult = @()
        $matchingResult = $result | Where-Object { ([system.uri]$dataResult.Resource).Scheme -in $_.Protocol -and ($dataResult.Resource -replace "https?://", "") -in $_.EndPoint}
        $matchingResult | Foreach-Object {
            Log-EndPointResult -Result $dataResult -Severity $PsItem.Severity -Name $PsItem.Name
            $dataResult.DebugDtls = 'redacted'
             # Create output
             $params = @{
                Name               = $PsItem.Name
                Title              = $PsItem.Title
                DisplayName        = $PsItem.Title
                Severity           = $PsItem.Severity
                Description        = $PsItem.Description
                Tags               = @{
                    Service        = $_.Service
                    Mandatory      = $_.Mandatory
                }
                Remediation        = $PsItem.Remediation
                TargetResourceID   = "$($dataResult.Source)/$($dataResult.Resource)"
                TargetResourceName = $dataResult.Resource
                TargetResourceType = $PsItem.TargetResourceType
                Timestamp          = $dataResult.TimeStamp
                Status             = $dataResult.Status
                AdditionalData     = $dataResult
                HealthCheckSource  = $ENV:EnvChkrId
            }
            $finalResult += New-AzStackHciResultObject @params
        }
    }
    return $finalResult
}

function Get-ProxyDiagnostics
{
    [CmdletBinding()]
    param(
        [Parameter()]
        [System.Management.Automation.Runspaces.PSSession[]]
        $PsSession
    )
    Log-Info "Gathering proxy diagnostics"
    $proxyConfigs = @()
    $proxyConfigsRecommendations = @()
    $proxyConfigConsistency = @()
    if ($PsSession)
    {
        foreach ($session in $PsSession)
        {
            $proxyConfigs += Get-WinHttpProxyHelper -PsSession $session
            $proxyConfigs += Get-ProxyEnvironmentVariable -PsSession $session
        }
    }
    else {
        $proxyConfigs += Get-WinHttpProxyHelper
        $proxyConfigs += Get-ProxyEnvironmentVariable
    }

    $proxyConfigConsistency += Test-ProxySettingsConsistency -ProxyConfig $proxyConfigs
    return ($proxyConfigs + $proxyConfigConsistency + $proxyConfigsRecommendations)
}

function Get-WinHttpProxyHelper
{
    [CmdletBinding()]
    param(
        [Parameter()]
        [System.Management.Automation.Runspaces.PSSession]
        $PsSession
    )
    Log-Info "Gathering WinHttp Proxy settings"
    $proxyHelperSb = {

        # gather machine scope proxy settings
        try {
            $line1, $line2, $line3, $JsonLines = netsh winhttp show advproxy
            $machineScope = $JsonLines #ConvertFrom-Json (-Join $JsonLines)
        }
        catch {
        }

        # Make sure we return the same object type as the other proxy functions
        $AdditionalData = @()
        $AdditionalData += @{
            Detail        = $machineScope
            Source        = $ENV:COMPUTERNAME
            Resource      = 'WinHttp'
            Status        = 'SUCCESS'
            TimeStamp    = [datetime]::UtcNow
        }
        return $AdditionalData
    }

    $winHttpOutput = if ($PsSession)
    {
        Invoke-Command -Session $PsSession -ScriptBlock $proxyHelperSb
        $TargetResourceName = "WinHttp_Proxy_$($PsSession.ComputerName)"
    }
    else
    {
        Invoke-Command -ScriptBlock $proxyHelperSb
        $TargetResourceName = "WinHttp_Proxy_$($ENV:COMPUTERNAME)"
    }

    # Write our findings to the log and create output objects
    $results = @()
    $results += foreach ($AdditionalData in $winHttpOutput | Sort-Object Source)
    {
        Log-Info "Machine Scope Proxy for $($AdditionalData.Source) (netsh winhttp show advproxy):"
        $AdditionalData.Detail | Format-List | Out-String -Stream | ForEach-Object {if (![string]::IsNullOrEmpty($_)){ Log-Info $_}}
        # Create output object
        $params = @{
            Name               = 'AzStackHci_Connectivity_Collect_Proxy_Diagnostics_WinHttp'
            Title              = 'WinHttp Proxy Settings'
            DisplayName        = "$($AdditionalData.Source) WinHttp Proxy Settings"
            Severity           = 'INFORMATIONAL'
            Description        = 'Collects proxy configuration for WinHttp'
            Tags               = @{
                Service = 'System'
            }
            Remediation        = "https://learn.microsoft.com/en-us/azure-stack/hci/manage/configure-proxy-settings#configure-proxy-settings-for-azure-stack-hci-operating-system"
            TargetResourceID   = "$($AdditionalData.Source)/$($AdditionalData.Resource)"
            TargetResourceName = $AdditionalData.Resource
            TargetResourceType = 'Proxy Settings'
            Timestamp          = [datetime]::UtcNow
            Status             = $AdditionalData.Status
            AdditionalData     = $AdditionalData
            HealthCheckSource  = $ENV:EnvChkrId
        }
        New-AzStackHciResultObject @params
    }
    return $results
}

function Get-ProxyEnvironmentVariable
{
    <#
    .SYNOPSIS
        Get Proxy configuration from environment variables
    .DESCRIPTION
        Get Proxy configuration from environment variables
    .EXAMPLE
        PS C:\> Get-ProxyEnvironmentVariable
        Explanation of what the example does
    .INPUTS
        URI
    .OUTPUTS
        Output (if any)
    .NOTES
    #>

    [CmdletBinding()]
    param (
        [Parameter()]
        [System.Management.Automation.Runspaces.PSSession]
        $PsSession
    )
    Log-Info "Gathering machine Proxy settings from environment variables"

    $envProxySb = {
        $AdditionalData = @()
        $AdditionalData += @{
            Detail      =  @{
                ProxyIsEnabled  = [bool]([Environment]::GetEnvironmentVariable("HTTPS_PROXY","MACHINE"))
                Proxy           = [Environment]::GetEnvironmentVariable("HTTPS_PROXY","MACHINE")
                ProxyBypass     = [Environment]::GetEnvironmentVariable("NO_PROXY","Machine")
            } | ConvertTo-Json
            Source      = $ENV:COMPUTERNAME
            Resource    = 'Environment'
            Status      = 'SUCCESS'
            TimeStamp    = [datetime]::UtcNow
        }
        return $AdditionalData
    }
    [array]$EnvironmentProxyOutput = if ($PsSession)
    {
        Invoke-Command -Session $PsSession -ScriptBlock $envProxySb
        $TargetResourceName = "Environment_Proxy_$($PsSession.ComputerName)"
    }
    else
    {
        Invoke-Command -ScriptBlock $envProxySb
        $TargetResourceName = "Environment_Proxy_$($ENV:COMPUTERNAME)"
    }
    # Write our findings to the log
    $results = @()
    $results += foreach ($AdditionalData in $EnvironmentProxyOutput | Sort-Object Source)
    {
        Log-Info "Environment Scope Proxy for $($AdditionalData.Source) (ENV:HTTPS_PROXY):"
        $AdditionalData.Detail | Format-List | Out-String -Stream | ForEach-Object {if (![string]::IsNullOrEmpty($_)){ Log-Info $_}}
        # Create output object
        $params = @{
            Name               = 'AzStackHci_Connectivity_Collect_Proxy_Diagnostics_Environment'
            Title              = 'Environment Proxy Settings'
            DisplayName        = "$($AdditionalData.Source) Environment Proxy Settings"
            Severity           = 'Information'
            Description        = 'Collects proxy configuration from environment variables'
            Tags               = @{
                Service = 'System'
            }
            Remediation        = "https://learn.microsoft.com/en-us/azure-stack/hci/manage/configure-proxy-settings#configure-proxy-settings-for-azure-arc-enabled-servers"
            TargetResourceID   = "$($AdditionalData.Source)/$($AdditionalData.Resource)"
            TargetResourceName = $AdditionalData.Resource
            TargetResourceType = 'Proxy Settings'
            Timestamp          = $AdditionalData.TimeStamp
            Status             = $AdditionalData.Status
            AdditionalData     = $AdditionalData
            HealthCheckSource  = $ENV:EnvChkrId
        }
        New-AzStackHciResultObject @params
    }
    return $results
}

function Test-ProxySettingsConsistency
{
    [CmdletBinding()]
    param(
        [Parameter()]
        [System.Array]
        $ProxyConfig
    )

    Log-Info "Testing all proxy settings are consistent"
    $simplifiedProxyConfig = Get-SimpleProxyConfigObject -ProxyConfig $ProxyConfig
    if (Compare-PSObjectArray -Array $simplifiedProxyConfig -Property Proxy)
    {
        # Check all winHttp are configured
        $dtl = $lcTxt.ProxySettingsConsistencyPass
        Log-Info $dtl
        $status = 'SUCCESS'
    }
    else
    {
        $dtl = $lcTxt.ProxySettingsConsistencyFail -f ([string]($simplifiedProxyConfig | Format-Table | Out-String) -replace '\r\n','')
        Log-Info $dtl -Type 'Critical'
        $status = 'FAILURE'
    }

    $params = @{
        Name               = 'AzStackHci_Connectivity_Proxy_Settings_Consistency'
        Title              = 'Proxy Settings Consistency'
        DisplayName        = "$($simplifiedProxyConfig.Source -join ',') Environment Proxy Settings"
        Severity           = 'Critical'
        Description        = 'Checks that all nodes are configured consistently for proxy settings'
        Tags               = @{
            Service = 'System'
        }
        Remediation        = "https://learn.microsoft.com/en-us/azure-stack/hci/manage/configure-proxy-settings"
        TargetResourceID   = "$($simplifiedProxyConfig.Source -join ',')/Proxy_Settings"
        TargetResourceName = "Proxy_Settings_AllServers"
        TargetResourceType = 'Proxy Settings'
        Timestamp          = [datetime]::UtcNow
        Status             = $Status
        AdditionalData     = @{
            Source = $simplifiedProxyConfig.Source -join ','
            Resource = 'Proxy Settings'
            Status = $status
            Detail = $dtl
            TimeStamp = [datetime]::UtcNow
        }
        HealthCheckSource  = $ENV:EnvChkrId
    }
    [array]$result = New-AzStackHciResultObject @params
    $ByPassCheck = Test-ProxyByPassListRecommendations -ProxyConfig $simplifiedProxyConfig
    return @($result + $ByPassCheck)
}

function Get-SimpleProxyConfigObject
{
    param(
        [Parameter()]
        [System.Array]
        $ProxyConfig
    )
    try {
        $simplifiedProxyConfig = @()
        $simplifiedProxyConfig += foreach ($p in $ProxyConfig)
        {
            $ProxyConfigObject = ConvertFrom-Json -InputObject $p.AdditionalData.Detail
            $hash = @{
                Source    = $p.AdditionalData.Source
                Resource  = $p.AdditionalData.Resource
                ProxyIsEnabled  = $ProxyConfigObject.ProxyIsEnabled
                Proxy           = $ProxyConfigObject.Proxy -replace 'http://|https://',''
                ProxyBypass     = $ProxyConfigObject.ProxyBypass -replace ';',','
            }
            New-Object -TypeName PsObject -Property $hash
        }
        return $simplifiedProxyConfig
    }
    catch {
        throw $_
    }

}

function Test-ProxyByPassListRecommendations
{
    [CmdletBinding()]
    param (
        [Parameter()]
        [System.Array]
        $ProxyConfig
    )

    if ($true -in $ProxyConfig.ProxyIsEnabled)
    {
        $requiredByPassList = @("localhost","127.0.0.1",".svc","10.0.0.0/8","172.16.0.0/12","192.168.0.0/16") # should also contain domain name, but we don't know that.
        Log-Info ($lcTxt.ProxyByPassListRecommendations -f ($requiredByPassList -join ','))

        $result = @()
        foreach ($config in $ProxyConfig)
        {
            # Check if each entry is present
            $missingByPassEntry = @()
            foreach ($entry in $requiredByPassList)
            {
                if ($entry -notin ($config.ProxyBypass -split ','))
                {
                    $missingByPassEntry += $entry
                }
            }

            # Set status based on missing entries
            if ($missingByPassEntry.count -gt 0)
            {
                $ByPassDtl = ($lcTxt.ProxyByPassListRecommendationsMissing -f ($missingByPassEntry -join ','), $config.Resource, $config.Source)
                Log-Info $ByPassDtl -Type Warning
                $status = 'FAILURE'
            }
            else
            {
                $ByPassDtl = ($lcTxt.ProxyByPassListRecommendationsPass -f $config.Resource, $config.Source)
                Log-Info $ByPassDtl
                $status = 'SUCCESS'
            }

            $params = @{
                Name               = 'AzStackHci_Connectivity_Proxy_ByPassList_Recommendations'
                Title              = 'Proxy ByPassList Recommendations'
                DisplayName        = "$($config.Source) Proxy ByPassList Recommendations"
                Severity           = 'WARNING'
                Description        = 'Checks that all nodes are configured with recommended proxy bypass list items'
                Tags               = @{
                    Service = 'System'
                }
                Remediation        = "https://learn.microsoft.com/en-us/azure-stack/hci/manage/configure-proxy-settings"
                TargetResourceID   = "$($config.Source)/Proxy_Bypass_List"
                TargetResourceName = $config.Resource
                TargetResourceType = 'Proxy Settings'
                Timestamp          = [datetime]::UtcNow
                Status             = $Status
                AdditionalData     = @{
                    Source    = $config.Source
                    Resource  = "Proxy_ByPassList_Recommendations_$($config.Source)"
                    Status    = $status
                    Detail    = $ByPassDtl
                    TimeStamp = [datetime]::UtcNow
                }
                HealthCheckSource  = $ENV:EnvChkrId
            }
            $result += New-AzStackHciResultObject @params

            #region Critical Failure for proxy bypass invalid entries
            [System.String] $bypassCriticalRstStatus = "SUCCESS"
            [System.String] $bypassCriticalRstDeail = "Entries in proxy bypass list in $($config.Resource) on $($config.Source) are valid."

            if ($config.ProxyBypass -match ",,")
            {
                $bypassCriticalRstStatus = "FAILURE"
                $bypassCriticalRstDeail = "Proxy bypass list contains ',,' in $($config.Resource) on $($config.Source)."
            }

            if ($config.ProxyBypass -match "<local>")
            {
                $bypassCriticalRstStatus = "FAILURE"
                $bypassCriticalRstDeail = "Proxy bypass list contains '<local>' in $($config.Resource) on $($config.Source)."
            }

            $proxyByPassInvalidEntriesCheckRstObject = @{
                Name               = 'AzStackHci_Connectivity_Proxy_ByPassList_InvalidEntries'
                Title              = 'Proxy ByPassList Invalid Entries'
                DisplayName        = "$($config.Source) Proxy Invalid Entries"
                Severity           = 'CRITICAL'
                Description        = 'Checks that all nodes proxy bypass list does not have invalid entries in it'
                Tags               = @{
                    Service = 'System'
                }
                Remediation        = "https://learn.microsoft.com/en-us/azure-stack/hci/manage/configure-proxy-settings"
                TargetResourceID   = "$($config.Source)/Proxy_Bypass_List"
                TargetResourceName = $config.Resource
                TargetResourceType = 'Proxy Settings'
                Timestamp          = [datetime]::UtcNow
                Status             = $bypassCriticalRstStatus
                AdditionalData     = @{
                    Source    = $config.Source
                    Resource  = "Proxy_ByPassList_InvalidEntries_$($config.Source)"
                    Detail    = $bypassCriticalRstDeail
                    Status    = $bypassCriticalRstStatus
                    TimeStamp = [datetime]::UtcNow
                }
                HealthCheckSource  = $ENV:EnvChkrId
            }

            $result += New-AzStackHciResultObject @proxyByPassInvalidEntriesCheckRstObject
            #endregion
        }
        return $result
    }
    else
    {
        Log-Info "No proxy is configured. Skipping proxy bypass list recommendations"
    }
}

function Write-FailedUrls
{
    [CmdletBinding()]
    param (
        $result
    )
    if (-not [string]::IsNullOrEmpty($Global:AzStackHciEnvironmentLogFile))
    {
        $file = Join-Path -Path (Split-Path $Global:AzStackHciEnvironmentLogFile -Parent) -ChildPath FailedUrls.txt
    }
    $FailedUrls = ($result.AdditionalData | Where-Object Status -NE 'SUCCESS').Resource
    if ($FailedUrls.count -gt 0)
    {
        Log-Info ("[Over]Writing {0} to {1}" -f ($FailedUrls -split ','), $file)
        $FailedUrls | Out-File $file -Force
        Log-Info "`nFailed Urls log: $file" -ConsoleOut
    }
}

function Select-AzStackHciConnectivityTarget
{
    <#
    .SYNOPSIS
        Apply user exclusions to Connectivity Targets
    #>


    [CmdletBinding()]
    param (
        [Parameter()]
        [psobject]
        $Targets,

        [Parameter()]
        [string[]]
        $Exclude,

        [Parameter()]
        [string]
        $FilePath = "$PSScriptRoot\..\ExcludeTests.txt"
    )

    try
    {
        $returnList = @($Targets)
        if ($exclude)
        {
            Log-Info "Removing tests $($exclude -join ',')"
            $returnList = $returnList | Where-Object { $_.Service | Select-String -Pattern $exclude -NotMatch }
        }
        if ($returnList.count -eq 0)
        {
            throw "No tests to perform after filtering"
        }
        if (Test-Path -Path $FilePath)
        {
            $fileExclusion = Get-Content -Path $FilePath
            Log-Info "Reading exclusion file $FilePath" -ConsoleOut
            Log-Info "Applying file exclusions: $($fileExclusion -join ',')" -ConsoleOut
            $returnList = $returnList | Where-Object {( $_.Service | Select-String -Pattern $fileExclusion -NotMatch ) -and ( $_.endpoint | Select-String -Pattern $fileExclusion -NotMatch )}
        }

        Log-Info "Test list: $($returnList -join ',')"
        if ($returnList.Count -eq 0)
        {
            Log-Info -Message "No tests to run." -ConsoleOut -Type Warning
            break noTestsBreak
        }
        return $returnList
    }
    catch
    {
        Log-Info "Failed to filter test list. Error: $($_.exception)" -Type Warning
    }
}

function Get-CloudEndpointFromManifest
{
    [CmdletBinding()]
    param (
        [Parameter()]
        [system.uri]
        $Uri = 'https://aka.ms/hciconnectivitytargets'
    )

    try
    {
        $tempXmlFile = Join-Path -Path $env:temp -ChildPath 'AzStackHciConnectivityTarget.xml'
        Write-Verbose "Retrieving connectivity targets from $Uri to temp location: $tempXmlFile..."
        $iwrParams = @{
            Uri = $Uri
            UseBasicParsing = $true
            OutFile = $tempXmlFile
        }
        $response = Invoke-WebRequest @iwrParams

        $testSigningScript = Join-Path -Path $PSScriptRoot -ChildPath 'TestXmlSigning.ps1'
        Write-Verbose "Validating signature of $tempXmlFile..."
        [bool]$checkSigningResult = Start-Job -PSVersion 5.1 -ScriptBlock { & $USING:testSigningScript $USING:tempXmlFile } | Wait-Job | Receive-Job -ErrorAction SilentlyContinue
        Write-Verbose "Signature validation result: $checkSigningResult"
        if (-not $checkSigningResult)
        {
            throw "Failed to validate signature of $tempXmlFile from $url"
        }
        [xml]$manifest = Get-Content -Path  $tempXmlFile
        $version = $manifest.Objects.Object.Property | Where-Object Name -eq Version | Select -ExpandProperty '#text'
        $title = $manifest.Objects.Object.Property | Where-Object Name -eq Title | Select -ExpandProperty '#text'
        $targets = $manifest.Objects.Object.Property | Where-Object Name -eq Targets | Select -ExpandProperty 'Property'
        [AzStackHciConnectivityTarget[]]$targets = New-AzStackHciConnectivityTargetFromXml -TargetXml $targets
        $msg = "Retrieved $($targets.count) connectivity targets from $($title) version $($version)"
        Write-Verbose $msg
        return $targets
    }
    catch
    {
        $msg = "Failed to get connectivity targets from $Uri. Error: $($_.exception.message)"
        Write-Verbose $msg
    }
    finally
    {
        if (Test-Path -Path $tempXmlFile)
        {
            Remove-Item -Path $tempXmlFile -ErrorAction SilentlyContinue
        }
    }
}


function Export-AzStackHciConnectivityTargetToXml
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]
        $TargetDirectory,

        [Parameter(Mandatory)]
        [string]
        $TargetFileName,

        [Parameter(Mandatory)]
        [string]
        $Version
    )
    $AzStackHciConnectivityTargets = Get-AzStackHciConnectivityTarget -LocalOnly -IncludeSystem
    Write-Host ("Found {0} connectivity targets for manifest" -f [int]($Script:AzStackHciConnectivityTargets.Count))
    Write-Host "Creating manifest with version $version"
    $manifest = New-Object AzStackHciConnectivityManifest -Property @{
        Title = 'AzStackHci Connectivity Endpoint Definitions'
        Version = $Version
        Targets = $Script:AzStackHciConnectivityTargets
    }
    $manifest | ConvertTo-Xml -Depth 5 -As Stream | Out-File $TargetDirectory\$TargetFileName -Encoding utf8
}

function New-AzStackHciConnectivityTargetFromXml
{
    param ($TargetXml)
    foreach ($target in $TargetXml)
    {
        $ErrorActionPreference = 'Stop'
        $AzStackHciConnectivityTargetObject = New-Object AzStackHciConnectivityTarget
        # Arrays
        'EndPoint', 'Protocol', 'Service', 'OperationType' | Foreach-Object {
            $AzStackHciConnectivityTargetObject.$PSITEM = ($target.Property | Where-Object Name -eq $PSITEM).ChildNodes.'#text'
        }

        # Booleans
        'Mandatory', 'System' | ForEach-Object {
            $AzStackHciConnectivityTargetObject.$PSITEM = if (($target.Property | Where-Object Name -eq $PSITEM).'#text' -eq 'True') { $true } else { $false }
        }

        # Strings
        'Name', 'Title', 'Severity', 'Description', 'Remediation', 'TargetResourceID', 'TargetResourceName', 'TargetResourceType', 'Group' | Foreach-Object {
            $AzStackHciConnectivityTargetObject.$PSITEM = ($target.Property | Where-Object Name -eq $PSITEM).'#text'
        }

        # Tags
        $ErrorActionPreference = 'SilentlyContinue'
        $tagsProperties = $target.Property | Where-Object Name -eq Tags | Select-Object -ExpandProperty Property

        $Groups = $tagsProperties | Where-Object Name -eq Group
        $Mandatory = $tagsProperties | Where-Object Name -eq Mandatory
        $Service = $tagsProperties | Where-Object Name -eq Service
        $OperationType = $tagsProperties | Where-Object Name -eq OperationType
        $ExpectedSubject = $tagsProperties | Where-Object Name -eq ExpectedSubject

        # Tags are optional, we iterate through them to
        $tagHash = @{}
        if ($Groups) { $tagHash += @{Group = $Groups.'#text'}}
        if ($Service) { $tagHash += @{Service = $Service.ChildNodes.'#text'}}
        if ($Mandatory) { $tagHash += @{Mandatory = if ($Mandatory.'#text' -eq 'True') { $true } else { $false }}}
        if ($OperationType) { $tagHash += @{OperationType = $OperationType.ChildNodes.'#text'}}
        if ($ExpectedSubject) { $tagHash += @{ExpectedSubject = $ExpectedSubject.ChildNodes.'#text'}}

        $AzStackHciConnectivityTargetObject.Tags = New-Object PsObject -Property $tagHash
        Write-Verbose $AzStackHciConnectivityTargetObject.Name
        $AzStackHciConnectivityTargetObject
    }
}

function Compare-PSObjectArray {
    param (
        [Parameter(Mandatory=$true)]
        [PSObject[]]$Array,
        [Parameter(Mandatory=$true)]
        [string[]]$property
    )

    # Get the first PSObject in the array
    $first = $Array[0]
    Log-Info "Comparing first object (below) objects with properties '$($property -join ',')':"
    Log-Info ($first | Sort-Object Source | Format-List | Out-String)

    # Compare the first PSObject to the rest of the PSObjects in the array
    $fail = @()
    for ($i = 1; $i -lt $Array.Count; $i++) {
        $result = Compare-Object $first $Array[$i] -Property $property
        # If the PSObjects do not match, return false
        if ($result) {
            $fail += $Array[$i]
        }
    }
    if ($fail.count -gt 0)
    {
        Log-Info "Objects properties '$($property -join ',')' do not match:"
        Log-Info ($fail | Sort-Object Source | Format-List | Out-String)
        return $false
    }
    # If all PSObjects match, return true
    return $true
}

# Convert PsObject to Hashtable
function ConvertTo-Hashtable {
    param (
        [Parameter(Mandatory=$true)]
        [PSObject]$Object
    )

    $hash = @{}
    foreach ($property in $Object.PsObject.Properties) {
        $hash[$property.Name] = $property.Value
    }
    return $hash
}
# SIG #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A4iUW5jILBuLWUSrw4hFBMRhTubWnoMV
# fZuBgEGMtvoJX4e4vn2/fV668r8o+sBBqSBzyllYd15gh5FmJO6RPygvPo1hC4pM
# WMkS8XTHo5Lv9KKugMpbjbaIswufq7a1+nGAZuHxZs36sOskDhzhsv0Oij5Ufz4j
# b4il1dItsN9keJ3cqhViXNohCIt1AobpUAQz5yHqvqVqRjERWc+HtSVlivcDlxgM
# LOAga5QKsRu3fhK2NY7fYbmBDYoV8pxbzQEmaCvWMJI1XunVpyWpzKCaKsyAzgfA
# D/yUBslQl7E2ecbwd0nb1ns=
# SIG # End signature block