Up 2 Down 0

Download, Extract and Import Certificate

This script checks if a specific certificate is already installed in Windows. If not, it downloads, extracts and installs the certificate to the Trusted Root Certification Authorities store.

$Thumbprint = "PLACE_THUMBPRINT_HERE_TO_CHECK_IF_ALREADY_INSTALLED"
$Link = "https://link.to/certificate.zip"
$User = "http_username"
$Pass = "http_password"
$File = "certificate.zip"
$Path = "C:\Users\Public\Downloads"
$CertFileName = "certificate.cer"
$certPath = Join-Path -Path $Path -ChildPath $CertFileName
$StoreName = "Root"
$StoreLocation = "LocalMachine"

function Test-CertificateExists {
    param(
        [Parameter(Mandatory=$true)]
        [string]$Thumbprint,
        [string]$StoreName = "Root",
        [string]$StoreLocation = "LocalMachine"
    )
    
    $store = New-Object System.Security.Cryptography.X509Certificates.X509Store($StoreName, $StoreLocation)
    $store.Open("ReadOnly")
    
    $certificate = $store.Certificates.Find("FindByThumbprint", $Thumbprint, $false)
    $exists = ($certificate.Count -gt 0)
    
    $store.Close()
    return $exists
}

function Import-CerCertificate {
    param(
        [String]$certPath,
        [String]$certRootStore = "LocalMachine",
        [String]$certStore = "Root"
    )
    
    try {
        # Create certificate object for .cer file
        $cert = new-object System.Security.Cryptography.X509Certificates.X509Certificate2($certPath)
        
        # Open the certificate store
        $store = new-object System.Security.Cryptography.X509Certificates.X509Store($certStore, $certRootStore)
        $store.open("MaxAllowed")
        
        # Add the certificate
        $store.add($cert)
        
        return $true
    }
    catch {
        Write-Host "Error importing certificate: $_" -ForegroundColor Red
        return $false
    }
    finally {
        # Always close the store if it was opened
        if ($store -ne $null) {
            $store.close()
        }
    }
}

if (Test-CertificateExists -Thumbprint $Thumbprint -StoreName $StoreName -StoreLocation $StoreLocation) {
    Write-Host "Certificate is already installed. Exiting script." -ForegroundColor Green
    exit
}

if (Test-Path "$Path\$File") {
  Remove-Item "$Path\$File"
}

$ProgressPreference = "SilentlyContinue"
Invoke-WebRequest -Uri $Link -OutFile "$Path\$File" -UseBasicParsing -Credential (New-Object PSCredential($User, (ConvertTo-SecureString -AsPlainText -Force -String $Pass)))
Expand-Archive "$Path\$File" $Path -Force

if (Test-Path $certPath) {
    $result = Import-CerCertificate -certPath $certPath -certRootStore $StoreLocation -certStore $StoreName
    
    if ($result) {
        Write-Host "Certificate imported successfully to Trusted Root Certification Authorities from $certPath" -ForegroundColor Green
    }
} else {
    Write-Host "Certificate file not found at $certPath" -ForegroundColor Red
}