certificates – Creating PEM file through PowerShell

I am trying to code a script to create a PEM certificate file in powershell. I am not sure if what I did is totally wrong, but when I tried to use the PEM file in and socat OPENSSL it returned the error:

$ socat OPENSSL-LISTEN:1337,cert=cert.pem,verify=0 -

socat(1209) E SSL_CTX_use_certificate_file(): error:0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag
#create certificate
$cert = New-SelfSignedCertificate `
    -Subject "MYHOSTNAME" `
    -TextExtension @("2.5.29.17={text}DNS=MYHOSTNAME&IPAddress=192.168.1.100") `
    -KeySpec Signature `
    -HashAlgorithm SHA256 `
    -KeyExportPolicy Exportable

#publicKey
$PublicKey = $cert.GetPublicKey();
$PublicKeyB64 = (Convert)::ToBase64String($PublicKey,"InsertLineBreaks");

#privateKey
$RSACng  = (System.Security.Cryptography.X509Certificates.RSACertificateExtensions)::GetRSAPrivateKey($cert);
$PrivateKey = $RSACng.Key;
$PrivateKeyByte = $PrivateKey.Export("PRIVATEBLOB");
$PrivateKeyB64 = (Convert)::ToBase64String($PrivateKeyByte,"InsertLineBreaks");

#createFile
$out = New-Object string() -ArgumentList 6;
$out(0) = "-----BEGIN PRIVATE KEY-----";
$out(1) = $PrivateKeyB64;
$out(2) = "-----END PRIVATE KEY-----"

$out(3) = "-----BEGIN CERTIFICATE-----"
$out(4) = $publicKeyB64;
$out(5) = "-----END CERTIFICATE-----"

(IO.File)::WriteAllLines("C:UsersPubliccert.pem",$out)

I am not sure if what I did is totally wrong, but I could not find any resource to help me proceed.

Some script that perform similar action of creating a PEM file in powershell or some tip about how to proceed could be value to help me fix this one.