Skip to content

Instantly share code, notes, and snippets.

@mercdev
Created August 24, 2017 17:43
Show Gist options
  • Save mercdev/3ad180e103b21857883a8ad884590152 to your computer and use it in GitHub Desktop.
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.
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 = "account.name@domain.corp","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