I believe some of the functionality from the commands below is only available in PowerShell v5 and newer.
Launch PowerShell and start by creating your code signing certificate.
New-SelfSignedCertificate -certstorelocation cert:\CurrentUser\my -dnsname "Sam Magee" -Type CodeSigningCert
This should generate a thumbprint, you’ll need this later.
Convert a plain text string (a secure password) into a secure string and then save the secure string into a variable.
$pwd = ConvertTo-SecureString -String "Password" -Force -AsPlainText
Export the pfx file, substitute the location, filename and thumbprint for your own
Export-PfxCertificate -Cert Cert:\CurrentUser\My\66EWR4R0997G7UY9JRTY3J4IU5UI6LO2E18F039BC -FilePath "D:\Sam’s-Cert.pfx" -Password $pwd
Export the crt file, substitute the location, filename and thumbprint for your own. This is the file you will install on the machine you want to run your signed PowerShell code.
Export-Certificate -Cert Cert:\CurrentUser\My\66EWR4R0997G7UY9JRTY3J4IU5UI6LO2E18F039BC -FilePath "D:\Sam’s-Cert.crt"
Now that you have your PFX file exported, double click on it to reinstall it on this machine. Install it for the Current User to overwrite the certificate we’ve just made. When asked to fill in the “Import options” tick the following:
- Enable strong private key protection. You will be prompted every time the private key is used by an application if you enable this option
- Mark the key as exportable. This will allow you to backup or transport your keys at a later time.
- Include all extended properties.
The top tick box will prevent malicious applications from being able to sign files as you. The second will allow you to port your key to another machine if needed or if you wipe your machine. The final option keeps the setting that tells the certificate to be a code signing certificate.
Get your code signing certificate from your cert volume.
$cert = @(Get-ChildItem Cert:\CurrentUser\My -codesigning)
Sign the PowerShell file with the certificate.
Set-AuthenticodeSignature "D:\test.ps1" $cert