Skip to content

Instantly share code, notes, and snippets.

@Varriount
Created July 19, 2024 20:34
Show Gist options
  • Save Varriount/5ea65ad3c82a3c90bdba00f9f6be7b9a to your computer and use it in GitHub Desktop.
Save Varriount/5ea65ad3c82a3c90bdba00f9f6be7b9a to your computer and use it in GitHub Desktop.
PowerShell script to export certificates from Window's Certificate Store (to WSL)
# Prompt user for a pattern
$pattern = Read-Host "Enter the regular expression to search for in the certificate subject"
# Get the certificates matching the pattern.
$certificates = Get-ChildItem -Recurse Cert:\LocalMachine\ `
| Where-Object PSIsContainer -eq $false `
| Where-Object Subject -cmatch $pattern
# Check if any certificates match the pattern.
if ($certificates.Count -eq 0) {
Write-Host "No certificates matched the pattern."
exit
}
# Display the matched certificates.
Write-Host "Matched certificates:"
$certificates `
| Select-Object `
-Property 'Subject','Issuer','NotBefore','NotAfter',* `
-ExcludeProperty 'PS*','RawData*' `
| Out-GridView
# Ask for confirmation before exporting.
$confirm = Read-Host "Do you want to export these certificates? (y/n)"
if ($confirm -ne 'y') {
Write-Host "Export cancelled."
exit
}
# Export the certificates.
$ErrorActionPreference = "Stop"
$certificates | ForEach-Object {
$subject = $_.Subject
$thumbprint = $_.Thumbprint
$name = "$subject - $thumbprint.pem"
$binaryFileName = "$name.der"
$base64FileName = "$name.pem"
Export-Certificate -Cert $_ -Type CERT -FilePath $binaryFileName
certutil.exe -encode $binaryFileName $base64FileName
}
Write-Host "Export finished."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment