Reputation: 101
I wrote a PS script where in it will import the certificate to the existing site to the IIS server, but i want a script where in it will match the thumbprint of the Cert which i am having with the thumbprint of the cert in the local machine store, if the thumbprint matches then import that certificate to the store, if not dont import the cert.
Example I have a pfx file with thumbprint = XXXXXX and the script need to be check if there are any thumbprint as same as above in my machine or in any remote server then the Cert which i am having need to be replaced or imported to the location.
Code
Clear-Host
$certPath = 'C:\TEMP\Sample.pfx'
$CertificatePassword = 'XXXXXX'
$SiteName = "SampleTest"
$HostName = "Sitebinding.com"
$SiteFolder = Join-Path -Path 'C:\inetpub\wwwroot' -ChildPath $SiteName
Write-Host 'Import pfx certificate' $certPath
$certRootStore = “LocalMachine”
$certStore = "My"
$pfx = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import($certPath,$CertificatePassword,"Exportable,PersistKeySet")
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store($certStore,$certRootStore)
$store.Open('ReadWrite')
$store.Add($pfx)
$store.Close()
$certThumbprint = $pfx.Thumbprint
#Write-Host 'Add website' $SiteName
#New-WebSite -Name $SiteName -PhysicalPath $SiteFolder -Force
#$IISSite = "IIS:\Sites\$SiteName"
#Set-ItemProperty $IISSite -name Bindings -value @{protocol="https";bindingInformation="*:443:$HostName"}
#if($applicationPool) { Set-ItemProperty $IISSite -name ApplicationPool -value $applicationPool}
Write-Host 'Bind certificate with Thumbprint' $certThumbprint
#$obj = get-webconfiguration "//sites/site[@name='$SiteName']"
$obj = Get-WebBinding $SiteName -Port 443
#$binding = $obj.bindings.Collection[0]
#$method = $binding.Methods["AddSslCertificate"]
$method = $obj.Methods["AddSslCertificate"]
$methodInstance = $method.CreateInstance()
$methodInstance.Input.SetAttributeValue("certificateHash", $certThumbprint)
$methodInstance.Input.SetAttributeValue("certificateStoreName", $certStore)
$methodInstance.Execute()```
Thanks In Advance.
Upvotes: 0
Views: 382
Reputation: 25031
It seems like you could do an if
statement that includes querying the Cert:
PSDrive
for the thumbprint. Then only update the binding based on the condition.
if (Get-ChildItem Cert:\LocalMachine -Recurse | Where Thumbprint -eq $certThumbprint) {
# Update Binding
}
Upvotes: 0