Private/Skip-CertificateCheck.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
Function Skip-CertificateCheck {
    <#
    .SYNOPSIS
    Bypass SSL Validation
 
    .DESCRIPTION
    Enables skipping of ssl certificate validation for current PowerShell session.
 
    .EXAMPLE
    Skip-CertificateCheck
 
    #>


    $CompilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters
    $CompilerParameters.GenerateExecutable = $false
    $CompilerParameters.GenerateInMemory = $true
    $CompilerParameters.IncludeDebugInformation = $false
    $CompilerParameters.ReferencedAssemblies.Add("System.DLL") | Out-Null
    $CertificatePolicy = @'
        namespace Local.ToolkitExtensions.Net.CertificatePolicy
        {
            public class TrustAll : System.Net.ICertificatePolicy
            {
                public bool CheckValidationResult(System.Net.ServicePoint sp,System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Net.WebRequest req, int problem)
                {
                    return true;
                }
            }
        }
'@


    if ( -not (Test-IsCoreCLR)) {

        $CSharpCodeProvider = New-Object Microsoft.CSharp.CSharpCodeProvider
        $PolicyResult = $CSharpCodeProvider.CompileAssemblyFromSource($CompilerParameters, $CertificatePolicy)
        $CompiledAssembly = $PolicyResult.CompiledAssembly
        ## Create an instance of TrustAll and attach it to the ServicePointManager
        $TrustAll = $CompiledAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
        [System.Net.ServicePointManager]::CertificatePolicy = $TrustAll

    }

}