$certPath = “F:\certificate\yourcertificate.pfx”
$certPass = “Certificate-password”
$pfx = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import($certPath,$certPass,”Exportable,PersistKeySet”)
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store(“My”,”LocalMachine”)
$store.Open(“ReadWrite”)
$store.Add($pfx)
$store.Close()
$certThumbprint = $pfx.Thumbprint
Write-host $certThumbprint
$serviceAccount = ‘IIS_IUSRS,IUSR’
$serviceAccounts = $serviceAccount.split(“,”);
foreach($l in $serviceAccounts)
{
write-host $l
$permissionType = ‘Read’
try
{
#Clear Existing Variables
$cert = ”
$keyFullPath = ”
Write-Host “————————–“
Write-Host “Server: $env:ComputerName” -ForegroundColor Cyan
Write-Host “Finding Certificate…” -ForegroundColor Green
#Get Certificate
$cert = Get-ChildItem -Path cert:\LocalMachine\My | Where-Object {$_.Thumbprint -eq ($certThumbprint -replace ‘\s’,”)}
If ($cert -ne $null -and $cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName -ne $null)
{
# Get Location of the machine related keys
$keyPath = $env:ProgramData + “\Microsoft\Crypto\RSA\MachineKeys\”;
$keyName = $cert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName;
$keyFullPath = $keyPath + $keyName;
Write-Host “Found Certificate…” -ForegroundColor Green
Write-Host “Granting access to $l…” -ForegroundColor Green
#Grant Full Control to account listed in $serviceAccount
$acl = (Get-Item $keyFullPath).GetAccessControl(‘Access’) #Get Current Access
$buildAcl = New-Object System.Security.AccessControl.FileSystemAccessRule($l,$permissionType,”Allow”) #Build Access Rule
$acl.SetAccessRule($buildAcl) #Add Access Rule
Set-Acl $keyFullPath $acl #Save Access Rules
Write-Host “Access granted to $l…” -ForegroundColor Green
Write-Host “————————–“
}
Else {
Write-Host “Unable to find Certificate that matches thumbprint $certThumbprint or the private key is missing…” -ForegroundColor Red
Write-Host “————————–“
}
}
catch
{
Write-Host “Unable to grant access to $l…” -ForegroundColor Yellow
Write-Host “————————–“
throw $_;
}
}
You required administration rights to
execute this script.