Copy certificates from one server to another

So for some reason, which until now remains a mystery, certificates where missing in the Trusted root certificate authorities certificate store on one of our servers.

Of course one of the missing ones, was the one needed for a main part of the servers purpose, so that had to be fixed.

While the certificates mmc does permit the export on the source server and the import onto the broken one, working in the GUI, is just….

So I cooked up a Powershell script to do the job for me:


Param(
	[Parameter(Mandatory=$true)][String]$SourceServer,
	[Parameter(Mandatory=$true)][String]$TargetServer,
	[Parameter(Mandatory=$true)]
		[ValidateSet("My","Root","CertificateAuthority","AuthRoot")]
		[String]$CertStore,
	[Parameter(Mandatory=$false)][switch]$write
)
#
#Connect to the source Root store (readonly)
$sourceStore = New-Object System.Security.Cryptography.X509Certificates.X509Store("\\$SourceServer\$CertStore","LocalMachine")
$sourceStore.open("ReadOnly")
#connect to the target store (readwrite)
$targetStore = New-Object System.Security.Cryptography.X509Certificates.X509Store("\\$TargetServer\$CertStore","LocalMachine")
$targetStore.open("ReadWrite")

$sourceCerts = $sourceStore.certificates
$targetCerts = $targetStore.certificates

Function CheckPrecense(){
Param(
    $sourcecert
)
	[int]$intCertFound = "0"
    $script:rtrCheckPrecense = "CertNotFound"
    ForEach ($targetcert in $targetCerts){     
        $test = $sourcecert.Equals($targetcert)
        if ($test -eq $true){
            $intCertFound++
        }
    }
    If ($intCertFound -ne "0"){
            $script:rtrCheckPrecense = "CertFound"
    }
} #end function 

foreach ($sourcecert in $sourceCerts){
    CheckPrecense $sourcecert
    If ($rtrCheckPrecense -eq "CertNotFound"){
        Write-Host `n`n $sourceCert.Subject " was not found on " $TargetServer
        If ($write -eq $true){
        	Write-Host `n "Copying Certificate from " $SourceServer `n
        	$targetStore.Add($sourceCert)
        }
    }
}

Don’t judge me by the fact that the .Synopsis part of the script takes up half the lines in the script, but not being a programmer by trade, I am trying to improve on my documentation skills (as well as making myself able to reuse the script once I have forgotten it’s original purpose)

The script can be easily modified to also remove certs from the target, which is not present on the source.

Do let me know all your input, thoughts etc.

 

/theadminguy