Skip to content

Instantly share code, notes, and snippets.

@jschlackman
Created October 16, 2025 01:29
Show Gist options
  • Save jschlackman/e9ca9394eb44e10c4e6d045511606d6b to your computer and use it in GitHub Desktop.
Save jschlackman/e9ca9394eb44e10c4e6d045511606d6b to your computer and use it in GitHub Desktop.
<#
.SYNOPSIS
Create a basic self-signed certificate for "testing" purposes and save it in a password-protected PFX file.
.DESCRIPTION
Author: James Schlackman
Last Modified: Oct 15 2025
.PARAMETER DnsName
One or more DNS names to put into the subject alternative name extension of the certificate. The first DNS name is also saved as the Subject Name.
.PARAMETER FilePath
Path for the PFX file to be exported.
.PARAMETER Password
Password used to protect the exported PFX file.
.PARAMETER KeyAlgorithm
Name of the algorithm that creates the asymmetric keys that are associated with the new certificate.
.PARAMETER KeyLength
Length, in bits, of the key that is associated with the new certificate.
.PARAMETER YearsUntilExpiry
Number of years from the current date that the certificate expires.
.PARAMETER RetainInStore
If specified, the new certifcate will be retained in the Current User certificate store instead of being removed once the PFX file is created.
#>
function New-SelfSignedPfx {
Param (
[Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String[]] $DnsName,
[Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String] $FilePath,
[Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [String] $Password,
[Parameter()] [ValidateNotNullOrEmpty()] [String] $KeyAlgorithm = 'RSA',
[Parameter()] [ValidateNotNullOrEmpty()] [Int32] $KeyLength = 2048,
[Parameter()] [ValidateNotNullOrEmpty()] [Int32] $YearsUntilExpiry = 5,
[Parameter()] [Switch] $RetainInStore
)
$newCert = New-SelfSignedCertificate -DnsName $DnsName -CertStoreLocation Cert:\CurrentUser\My -KeyAlgorithm $KeyAlgorithm -KeyLength $KeyLength -NotAfter (Get-Date).AddYears($YearsUntilExpiry)
# If a cert was successfully created, export it
If ($newCert) {
$pfxPwd = ConvertTo-SecureString -String $Password -Force -AsPlainText
$newCert | Export-PfxCertificate -FilePath $FilePath -Password $pfxPwd
# Remove the new cert from the store unless switch specified to keep it there
If (!$RetainInStore) {
$newCert | Remove-Item
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment