How to create a self-signed certificate using powershell

Didn’t know, but it seems that you can create a self-signed certificate using Powershell!

The commands you need are New-SelfSignedCertificate and Export-PfxCertificate

Set-ExecutionPolicy RemoteSigned

$certificateFriendlyName = “MyCertificate”
$certificateDns = “localhost”
$certificatePassword = ConvertTo-SecureString -String “MyPassword” -Force –AsPlainText
$exportDirectory = “C:\Certs”
$exportFileName = “localhost.pfx”
$exportLocation = “$exportDirectory\$exportFileName”

New-Item -ItemType Directory -Force -Path $exportDirectory

$certificate=(dir cert:\localmachine\My -recurse | where {$_.FriendlyName -match $certificateFriendlyName} | Select-Object -Last 1).thumbprint

if ($certificate.Length -gt 0)
{
Write-Host “Duplicated Cert Name used” -ForegroundColor Cyan
return
}
else
{
$certificate = New-SelfSignedCertificate -DnsName $certificateDns -CertStoreLocation cert:\LocalMachine\My -FriendlyName $certificateFriendlyName
$certificatePath = “cert:\LocalMachine\My\” + $certificate.Thumbprint

Export-PfxCertificate -Cert $certificatePath -FilePath $exportLocation -Password $certificatePassword
}

 

Advertisements