PoshCode Archive  Artifact [55214d6ee1]

Artifact 55214d6ee108752b6b9cfba399fc70e13b824b49e1797a0c0139d7043f406c43:

  • File Manage-Service-Certs.ps1 — part of check-in [8ea6048e5e] at 2018-06-10 14:04:51 on branch trunk — Manages service certificate stores. (user: Mokstar size: 1877)

# encoding: ascii
# api: csharp
# title: Manage Service Certs
# description: Manages service certificate stores.
# version: 0.1
# type: class
# author: Mokstar
# license: CC0
# function: Update-ServiceCertificate
# x-poshcode-id: 5958
# x-archived: 2015-08-02T00:52:30
# x-published: 2015-07-31T20:44:00
#
#
Add-Type @"
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace System.Security.Cryptography.X509Certificates{
    public class Helpers {                 
        [DllImport("crypt32.dll", EntryPoint="CertOpenStore", CharSet=CharSet.Auto, SetLastError=true)]
        public static extern IntPtr CertOpenStoreStringPara(int storeProvider, int encodingType, IntPtr hcryptProv, int flags, String pvPara); 
        }
    }
"@

Function Update-ServiceCertificate ($Service, $PFXPath, $PFXPass = '') {
    $pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2 
    $pfx.import($PFXPath,$pfxPass,"PersistKeySet") 
    $certStorePt = [System.Security.Cryptography.X509Certificates.Helpers]::CertOpenStoreStringPara(13, 0, 0, 344064, "$Service\My")
    $certStore = [System.Security.Cryptography.X509Certificates.X509Store]$certStorePt
    foreach ($Certificate in $certStore.Certificates) {
            if ($Certificate.Subject -match $pfx.subject){
                write-output 'Removing Cert:'
                $Certificate | select FriendlyName, SerialNumber, Thumbprint, Subject, Issuer, NotAfter, NotBefore | fl
                $CertStore.Remove($Certificate) 
                }
        }

    write-output "Adding Cert:"
    $pfx | select FriendlyName, SerialNumber, Thumbprint, Subject, Issuer, NotAfter, NotBefore | fl
    $certStore.Add($pfx) 
    $certStore.Close() 
    }