Created
August 24, 2017 17:43
-
-
Save mercdev/3ad180e103b21857883a8ad884590152 to your computer and use it in GitHub Desktop.
Get-Certificate by DNS Subject Name and grant management permissions. Will attempt to create via CA if not found.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cls | |
$dnssubject = 'CN=servername.goes.here' | |
$WorkingCert = Get-ChildItem CERT:\LocalMachine\My |where {$_.Subject -match $dnssubject} | sort $_.NotAfter -Descending | select -first 1 | |
if ($WorkingCert -eq $null) | |
{ | |
Write-Host "Unable to locate certificate for $($dnssubject), attempting to create..." | |
[string[]] $dnsnames = @("alternate.name.one", "altername.name.two", "alternate.name.three") | |
# $WorkingCert will be a Microsoft.CertificateServices.Commands.EnrollmentResult | |
# to see all available templates, use certutil: | |
# certutil -template | Select-String -Pattern TemplatePropCommonName | |
$WorkingCert = Get-Certificate -Template TemplatePropCommonName.Here -SubjectName $dnssubject -DnsName $dnsnames -CertStoreLocation cert:\LocalMachine\My | |
Write-Host "Certificate created." | |
} | |
try | |
{ | |
#$TPrint = $WorkingCert.Thumbprint | |
$rsaFile = $WorkingCert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName | |
} | |
catch | |
{ | |
Write-Host "Error: unable to locate certificate for $($dnssubject)" | |
Exit | |
} | |
$keyPath = "C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys\" | |
$fullPath = $keyPath + $rsaFile | |
$acl = Get-Acl -Path $fullPath | |
$permission = "[email protected]","FullControl","Allow" | |
$accessRule = new-object System.Security.AccessControl.FileSystemAccessRule $permission | |
$acl.AddAccessRule($accessRule) | |
try | |
{ | |
Set-Acl $fullPath $acl | |
Write-Host "Success: ACL set on certificate" | |
} | |
catch | |
{ | |
Write-Host "Error: unable to set ACL on certificate" | |
Exit | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment