$ErrorActionPreference = 'Stop' $scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path $certCandidates = @( (Join-Path $scriptDir 'connpack-root-ca.cer'), (Join-Path $scriptDir 'connpack-root-ca.crt') ) $certPath = $certCandidates | Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1 if (-not $certPath) { Write-Host 'ERROR: Certificate file not found. Place connpack-root-ca.cer or connpack-root-ca.crt next to this script.' -ForegroundColor Red exit 2 } try { $null = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($certPath) } catch { Write-Host ('ERROR: Invalid certificate file: ' + $certPath) -ForegroundColor Red exit 3 } $isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()) .IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) $importCertificateCmd = Get-Command -Name 'Import-Certificate' -ErrorAction SilentlyContinue $certutilCmd = Get-Command -Name 'certutil.exe' -ErrorAction SilentlyContinue function Try-ImportCertificate { param( [string]$FilePath, [string]$Store ) if (-not $importCertificateCmd) { return $false } try { Import-Certificate -FilePath $FilePath -CertStoreLocation $Store | Out-Null return $true } catch { return $false } } function Try-CertUtilImport { param( [string]$FilePath, [bool]$UseCurrentUser ) if (-not $certutilCmd) { return $false } $args = @() if ($UseCurrentUser) { $args += '-user' } $args += @('-addstore', 'Root', $FilePath) & $certutilCmd.Source @args | Out-Null return ($LASTEXITCODE -eq 0) } $installedStore = $null if ($isAdmin) { $localMachineInstalled = (Try-ImportCertificate -FilePath $certPath -Store 'Cert:\LocalMachine\Root') -or (Try-CertUtilImport -FilePath $certPath -UseCurrentUser $false) if ($localMachineInstalled) { $installedStore = 'LocalMachine\\Root' } else { Write-Host 'INFO: LocalMachine import failed. Trying CurrentUser store.' } } if (-not $installedStore) { $currentUserInstalled = (Try-ImportCertificate -FilePath $certPath -Store 'Cert:\CurrentUser\Root') -or (Try-CertUtilImport -FilePath $certPath -UseCurrentUser $true) if ($currentUserInstalled) { $installedStore = 'CurrentUser\\Root' } } if ($installedStore) { Write-Host ('SUCCESS: ConnPack root certificate installed to ' + $installedStore + '.') -ForegroundColor Green exit 0 } if (-not $importCertificateCmd -and -not $certutilCmd) { Write-Host 'ERROR: No certificate import tool is available (Import-Certificate/certutil).' -ForegroundColor Red } else { Write-Host 'ERROR: Failed to install the certificate into a trusted root store.' -ForegroundColor Red } exit 4