Sitecore And New-SelfSignedCertificate Issues with PowerShell 7

Sitecore developers often use PowerShell to create new self signed certificates in their work. New-SelfSignedCertificate and Export-PfxCertificate worked great in PowerShell 5.1, but PowerShell 7 has an open issue making it difficult. Fortunately, there is a workaround. Merging this into a snippet from Mihály Árvai gives us the following code:

Import-Module PKI -UseWindowsPowerShell

$session = Get-PSSession -Name WinPSCompatSession
$secPw = Read-Host -Prompt "Enter password" -AsSecureString
$pfxPath = '.\SitecoreIdentityTokenSigning.pfx'
$outPath = '.\secrets\sitecore-identitycertificate.txt'

Invoke-Command $session {
    $cert = New-SelfSignedCertificate -DnsName "localhost" `
            -FriendlyName "Sitecore Identity Token Signing" `
            -NotAfter (Get-Date).AddYears(5) `
            -KeyExportPolicy 'Exportable'
    Export-PfxCertificate -Cert $cert `
            -Path $pfxPath `
            -Password $using:SecPw | Out-Null 
        (Get-Item $pfxPath))
) | Out-File -Encoding ascii `
             -NoNewline `
             -Confirm `
             -Path $outPath