Home » PowerShell » PowerShell Export Certificate to PEM

PowerShell Export Certificate to PEM

PEM (Privacy Enhanced Mail) is a Base64 encoded file that contains encoded certificate information. In PowerShell to export the certificate to the PEM file, use the [System.Convert]::ToBase64String() method to convert certificate raw data into PEM format.

PowerShell Export Certificate to PEM format
PowerShell Export Certificate to PEM format

In this article, we will discuss how to export a certificate to PEM format using PowerShell.

PowerShell Export Certificate to PEM Format

Use the Get-ChildItem cmdlet in PowerShell to get the certificate by thumbprint. PEM format is a Base64 encoded file that contains raw data with Header and Footer.

Use the following PowerShell script to save the certificate to PEM format.

# Get UA application certificate by thumbprint
$uacert = Get-ChildItem 'Cert:\LocalMachine\UA Applications\841048409E5E81AF553A6FA599F0D7EA8C2F5C08'

# Exported PEM file path
$uacertFile = 'D:\exported_ua.pem'

# Convert UA certificate raw data to Base64
$pemFileContent = @(
 '-----BEGIN CERTIFICATE-----'
 [System.Convert]::ToBase64String($uacert.RawData, 'InsertLineBreaks')
 '-----END CERTIFICATE-----'
) 

# Output PEM file to the path
$pemFileContent | Out-File -FilePath $uacertFile -Encoding ascii

In the above PowerShell script, the $uacert variable contains the certificate details retrieved using the thumbprint. The $uacertFile variable contains the file path where the PEM file is to be exported.

$pemFileContaint variable contains the Base64 encoded view of $uacert raw data and added Header and footer information. System.Convert]::ToBase64String() method is used to convert the certificate raw data with line breaks into Base64 view.

Using the Out-File cmdlet in PowerShell, the $pemFileContent data is exported to the PEM format with encoding ascii format.

The output of the above PowerShell script creates a exported_ua.pem file at the D:\ drive location.

Cool Tip: How to export the certificate with a private key in PowerShell!

Conclusion

I hope the above article on how to export a certificate to PEM format using PowerShell is helpful to you.

You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.