Powershell and Certificate Chain
On Windows, and need to generate a certificate chain to a server? This script creates one file per certificate in the chain:
$destination = 'foo'
$webRequest = [Net.WebRequest]::Create(https:// + $destination)
$webRequest.AllowAutoRedirect = $FALSE
$webRequest.Method = 'HEAD'
$webRequest.Timeout = 1000
try {
"Connecting to $destination... " | Write-Host -NoNewline
$webRequest.GetResponse().HResult | Write-Host
}
catch [System.Net.WebException] {
$_.Exception.Status | Write-Host
if ( $_.Exception.Status -ne 'Timeout' ) {
throw $_
}
}
"Building certificate chain..." | Write-Host
$chain = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Chain
$chain.build( $webRequest.ServicePoint.Certificate ) | Out-Null
$contentType = [Security.Cryptography.X509Certificates.X509ContentType]::Cert
"Saving..." | Write-Host
# Skip server certificate
$chain.ChainElements.Certificate | Select-Object -Skip 1 | ForEach-Object {
set-content `
-value $( $_.Export( $contentType ) ) `
-path "$pwd\$( $_.Thumbprint ).cer" `
-encoding byte
$_
} | Format-Table | Out-String | Write-Host