How to create a Self Signed Certificate in PowerShell

There are the commands to create a Self-Signed Certificate in PowerShell. Open PS in Administrator mode.

#Set Name of the certificate
$domain = "domain.name"

#Path to save the files .cer and .pfx
$path = "c:\data\"

#Password of the PFX
$pwd = ConvertTo-SecureString -String "9DhZQQxaiHfIpMVW0pu9pEYX" -Force -AsPlainText

#Generate the certificate in the certification store
New-SelfSignedCertificate -DnsName $domain -CertStoreLocation "Cert:\LocalMachine\My"

#Recovery certificate from certification store
$cert = Get-ChildItem -Path "Cert:\LocalMachine\My" | Where-Object { $_.Subject -match $domain }

#Save the certificate in a file .cer (Only Public Key)
Export-Certificate -Cert $cert -FilePath "$path.cer" -Type CERT

#Save the certificate in a file .pfx (include Public and Private Key)
Export-PfxCertificate -Cert $cert -FilePath "$path.pfx" -Password $pwd