Skip to content

Instantly share code, notes, and snippets.

@Dan1el42
Last active August 29, 2015 14:07
Show Gist options
  • Save Dan1el42/970e1d43b69baa9dfdfe to your computer and use it in GitHub Desktop.
Save Dan1el42/970e1d43b69baa9dfdfe to your computer and use it in GitHub Desktop.
Copy the active SMS encryption certificate to the My store to enable access to the private key for the DSC Local Configuration Manager to decrypt credentials
<#
.SYNOPSIS
Copy the active SMS encryption certificate to the My store
.DESCRIPTION
Copy the active SMS encryption certificate to the My store to enable access to the private key for the DSC Local Configuration Manager to decrypt credentials
#>
Param
(
[String] $SMSCertificateFriendlyName = 'SMS Encryption Certificate'
)
# Get SMS encryption certificates sorted from SMS store
$SMSStoreCertsArray =
@(Get-ChildItem -Path Cert:\LocalMachine\SMS |
Where-Object { $_.FriendlyName -eq $SMSCertificateFriendlyName } |
Sort-Object -Property NotAfter -Descending)
# Copy most recent certificate from SMS to My store and remove old (inactive) certificates
$ActiveCertificate = $null
for ($i = 0; $i -lt $SMSStoreCertsArray.Count; $i++)
{
$Certificate = $SMSStoreCertsArray[$i]
if ($i -eq 0)
{
$ActiveCertificate = $Certificate
# Only copy if certificate does not exist in My store
if (-not (Test-Path -Path "Cert:\LocalMachine\My\$($Certificate.Thumbprint)"))
{
$Store = Get-Item -Path Cert:\LocalMachine\My
$Store.Open('ReadWrite')
try
{
$Store.Add($ActiveCertificate)
}
finally
{
$Store.Close()
}
}
}
else
{
$Certificate | Remove-Item -Force
}
}
# Remove old (inactive) SMS encryption certificates from the My store but leave the active certificate in-place
if ($ActiveCertificate)
{
# Get SMS encryption certificates from My/Personal store
$MyStoreCertsArray =
@(Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object { $_.FriendlyName -eq $SMSCertificateFriendlyName })
foreach ($Certificate in $MyStoreCertsArray)
{
if ($Certificate.Thumbprint -ne $ActiveCertificate.Thumbprint)
{
$Certificate | Remove-Item -Force
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment