03 August 2021

Convert .cer .p12 and .pfx files to .pem files in bulk with PowerShell

One of those things I have to do every year or so, and rather than doing things by hand, let PowerShell help me out.

<#
  .Synopsis
     Covert .cer to .pem 
  .DESCRIPTION
     This script converts .cer, .p12, and .pfx certificate files to .pem files
     Just define the source folder and the target folder
  .Created by
     Edwin van Brenk
  .Created for
     vanbrenk.blogspot.com
  .Date
     03-08-2021
  .Version
     1.0
  #>            
              
            
# Copy your .cer files to the temp dir below                        
mkdir C:\Temp\CerToPEM\cerfolder 2> $null                        
$cerfolder = "C:\Temp\CerToPEM\cerfolder"                        
# Copy your .p12 files to the temp dir below                        
mkdir C:\Temp\CerToPEM\p12folder 2> $null                        
$p12folder = "C:\Temp\CerToPEM\p12folder"                        
# Copy your .pfx files to the temp dir below                        
mkdir C:\Temp\CerToPEM\pfxfolder 2> $null                        
$pfxfolder = "C:\Temp\CerToPEM\pfxfolder"                        
# The new .pem files will end up in this folder                        
mkdir C:\Temp\CerToPEM\pemfolder 2> $null                        
$pemfolder = "C:\Temp\CerToPEM\pemfolder"             
            
            
#Function to convert .cer, .pem, .p12 and .pfx certs to .pem             
function convert {            
            
Get-ChildItem $cerfolder\*.cer | ForEach-Object {            
  certutil -encode $_.FullName ("{0}\{1}.pem" -f $_.DirectoryName,$_.BaseName)            
}            
            
Get-ChildItem $p12folder\*.p12 | ForEach-Object {            
  certutil -encode $_.FullName ("{0}\{1}.pem" -f $_.DirectoryName,$_.BaseName)            
}            
            
Get-ChildItem $pfxfolder\*.pfx | ForEach-Object {            
  certutil -encode $_.FullName ("{0}\{1}.pem" -f $_.DirectoryName,$_.BaseName)            
}            
}            
            
convert            
             
# After converting you can move the .pem files out of the source folder into the .pem destination folder            
Move-Item $cerfolder\*.pem -Destination $pemfolder            
Move-Item $p12folder\*.pem -Destination $pemfolder            
Move-Item $pfxfolder\*.pem -Destination $pemfolder            

No comments:

Post a Comment