PoshCode Archive  Artifact [c1540b2acc]

Artifact c1540b2acce13a3fabde4ea1f72b3d1b8482974ec702defdaca8dc890cfe5477:

  • File Import-PfxCertificate.ps1 — part of check-in [af0c846e8a] at 2018-06-10 13:40:38 on branch trunk — Import certificate files to the cert store (user: Joel Bennett size: 2248)

# encoding: ascii
# api: powershell
# title: Import-PfxCertificate
# description: Import certificate files to the cert store
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: Import-PfxCertificate
# x-poshcode-id: 4418
# x-archived: 2014-10-15T03:58:11
# x-published: 2014-08-26T18:22:00
#
#
function Import-PfxCertificate {
    #.Synopsis
    #  Import a pfx certificate to the specified local certificate store
    #.Example
    #  Import-PfxCertificate CodeSigning.pfx Cert:\CurrentUser\My
    #
    #  Imports a certificate from a file to the current user's personal cert store
    [CmdletBinding()]
    param( 
        # The cert file to import: defaults to all .pfx files in the current directory
        [Parameter(ValueFromPipelineByPropertyName=$true, Position=0)]
        [Alias("PSPath")]
        [String]$PfxCertificatePath = "*.pfx", 
        # The certificate store path
        [Parameter(ValueFromPipelineByPropertyName=$true, Position=1)]
        [Alias("Target","Store")]
        [String]$CertificateStorePath = "Cert:\CurrentUser\My"
    )

    process {
        $store = Get-Item $CertificateStorePath -EA 0 -EV StoreError | Where { $_ -is [System.Security.Cryptography.X509Certificates.X509Store] }
        if(!$Store) {
            $store = Get-Item Cert:\$CertificateStorePath -EA 0| Where { $_ -is [System.Security.Cryptography.X509Certificates.X509Store] }
            if(!$Store) { throw "Couldn't find X509 Certificate Store: $StoreError" }
            $CertificateStorePath = "Cert:\$CertificateStorePath"
        }

        try {
            $store.Open("MaxAllowed")
        } catch {
            throw "Couldn't open x509 Certificate Store: $_"
        }

        foreach($certFile in Get-Item $PfxCertificatePath) {
            Write-Warning "Attempting to load $($certfile.Name)"
            $cert = Get-PfxCertificate $certFile # May prompt for password
            if(!$cert) {
                Write-Warning "Failed to load $($certfile.Name)"
                continue
            }
            $store.Add($cert)

            Get-Item "${CertificateStorePath}$($cert.Thumbprint)"
        }
        $store.Close()
    }
}