Skip to content

Instantly share code, notes, and snippets.

@ergoz
Forked from smaglio81/Import-PfxCertificate.ps1
Created October 29, 2024 01:09
Show Gist options
  • Save ergoz/638703f3dafcff93abcf8aca16a35783 to your computer and use it in GitHub Desktop.
Save ergoz/638703f3dafcff93abcf8aca16a35783 to your computer and use it in GitHub Desktop.
<#
.SYNOPSIS
Imports a .pfx certificate onto a server
http://www.orcsweb.com/blog/james/powershell-ing-on-windows-server-how-to-import-certificates-using-powershell/
Use the given certificate information to load up and import a pfx certificate. This
should be execute on the server that the certificate is going to be imported into.
.PARAMETER CertPath
The physical to a certificate file
.PARAMETER CertRootStore
[Default CurrentUser]
The root certificate store to save th certificate in. The possible options are 'CurrentUser' or 'LocalMachine'.
.PARAMETER CertStore
[Default My]
The certificate store to save the certificate in. There are alot of options. Generally this is either
'My' or 'Root'.
.PARAMETER PfxPass
[Defualt $null]
The password needed to use a given certificate (.pfx).
.EXAMPLE
#>
Function Import-PfxCertificate {
Param(
[Parameter(Mandatory = $true)]
[String]$CertPath,
[ValidateSet("CurrentUser","LocalMachine")]
[String]$CertRootStore = "LocalMachine",
[String]$CertStore = "My",
$PfxPass = $null
)
Process {
$pfx = new-object System.Security.Cryptography.X509Certificates.X509Certificate2
if ($pfxPass -eq $null) {$pfxPass = read-host "Enter the pfx password" -assecurestring}
$pfx.import($certPath,$pfxPass,"Exportable,PersistKeySet")
$store = new-object System.Security.Cryptography.X509Certificates.X509Store($certStore,$certRootStore)
$serverName = [System.Net.Dns]::GetHostName();
Write-Warning ("Adding certificate " + $pfx.FriendlyName + " to $CertRootStore/$CertStore on $serverName. Thumbprint = " + $pfx.Thumbprint)
$store.open("MaxAllowed")
$store.add($pfx)
$store.close()
Write-Host ("Added certificate " + $pfx.FriendlyName + " to $CertRootStore/$CertStore on $serverName. Thumbprint = " + $pfx.Thumbprint)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment