Retrieve IIS Client mapping certificates


Hi All,

Below is the snippet to retrieve the client mapping certificate from IIS .

$siteName = "WebSiteName"

# Get build folder path

$ScriptPath = $MyInvocation.MyCommand.Path

# Get build folder parent directory

$ScriptDir = Split-Path -Parent $ScriptPath

[string] $logdate =get-date -Format "yyyyMMddhhmm"

$OutputFolderPath = $ScriptDir + "\Certificates"

if(!(Test-Path $OutputFolderPath))

{

New-Item -ItemType directory -Path $OutputFolderPath

}

$OutputFolderFilepath =$OutputFolderPath + "\" + "$logdate"

if(!(Test-Path $OutputFolderFilepath))

{

New-Item -ItemType directory -Path $OutputFolderFilepath

}

$authentications = Get-WebConfiguration `

-filter "system.webServer/security/authentication/*" `

-PSPath "IIS:\Sites\$siteName"

foreach ($auth in $authentications)

{

if ($auth.sectionpath -like ‘*iisClientCertificateMappingAuthentication*’)

{

$IISMappings=$auth

}

}

$certCollection=$IISMappings|select -ExpandProperty oneToOneMappings|select -expandproperty collection

$count=$certCollection.Count;

for( $i=0; $i -le $count; $i++)

{

$cert= $certCollection[$i].certificate

$Certname="Cert"+$i

$certPath=$OutputFolderFilepath+"\$Certname.cer"

$cert| Set-Content -Path "$certPath" -Force

}

$certList = Get-ChildItem $OutputFolderFilepath

$IISCerts=@()

foreach ($cer in $certList)

{

$certPrint = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2

$certPrint.Import($cer.fullname)

# Write-Host $cer.Name,$certPrint.SerialNumber

$IISCerts +=[pscustomobject][ordered]@{CertificateName=$cer.Name

CertificateSerialNumber=$certPrint.SerialNumber

CertificateExpirydate=$certPrint.NotAfter

Subject=$certPrint.Subject

}

}

$IISCerts|?{$_.CertificateExpirydate -ge (Get-Date)}|Export-Csv -Path $OutputFolderFilepath -NoTypeInformation

regards,

Chaitanya

Leave a comment