function Find-CertificateByName { <# .SYNOPSIS Finds and returns a certificate from the certificates stores with a common name. .PARAMETER CommonName The Common Name of the certificate to search for. .PARAMETER StoreLocation The certificate store location. CurrentUser or LocalMachine .PARAMETER StoreName The name of the certificate store to search. #> Param( [Parameter(Mandatory=$true)] [String] $CommonName, [Parameter(Mandatory=$true)] [ValidateSet("CurrentUser", "LocalMachine")] [String] $StoreLocation, [Parameter(Mandatory=$true)] [ValidateSet("My", "CA", "Root", "TrustedPeople")] [String] $StoreName ) $loglead = (Get-LogLeadName); # Get all of the certificates from the specified certificate store. $storePath = "Cert:\$StoreLocation\$StoreName"; Write-Verbose "$loglead Searching for certificate with Common Name '$CommonName' in store path '$storePath'"; [array]$allCerts = (Get-ChildItem -Path $storePath); # Find all of the certs that have the common name we are looking for. $certificates = @(); foreach($cert in $allCerts) { # Parse out the common name. $subjectSplit = $cert.Subject.Split(","); foreach($ss in $subjectSplit) { $propertySplit = $ss.Split("="); if($propertySplit.Count -ne 2) { continue; } $key = $propertySplit[0].Trim(); $value = $propertySplit[1].Trim(); # If the common name matches the certificate we are looking for, store the cert. if(($key -eq "CN") -and ($value -eq $CommonName)) { $certificates += $cert; break; } } } # Return if the certificate could not be found. if(Test-IsCollectionNullOrEmpty $certificates) { Write-Warning "$loglead Could not find certificate with Common Name $CommonName"; return $null; } # Sort the certificates by their issue date to pick the latest issued cert. $certificates = ($certificates | Sort-Object -Property "NotBefore" -Descending); # Write-out all of the certificates that we found. foreach($cert in $certificates) { Write-Verbose "$loglead Found certificate with thumbprint $($cert.Thumbprint)" } # Return the top certificate that was found. return ($certificates | Select-Object -First 1); }