I wanted to allow all signed Powershell scripts to run on a PC in our house on Windows 10. To do that, I needed a code-signing certificate.
Unfortunately, the days of easily obtaining a free code signing certificate seem to have ended. Have no fear! You can create a self-signed certificate if you don’t expect to use the certificate anywhere but on the PC where the certificate was created.
First, I enabled Powershell scripts to run. From an administrative Powershell command prompt:
> Set-ExecutionPolicy AllSigned
Acknowledge the warning and you’re ready to execute only signed scripts.
But, if you create your own script, you’ll need to sign it. To create the necessary code-signing certificate, you’ll again use Powershell. From an administrative Powershell command prompt:
PS C:\Dev>New-SelfSignedCertificate -CertStoreLocation Cert:\LocalMachine\ -Type CodeSigningCert -Subject "CN=PowershellScripts" -NotAfter (Get-Date).AddYears(10)
You can change the Common Name (CN) to anything you’d like, or adjust the expiration date (using -NotAfter). I’ve got the expiration as 10 years from today.
Once you’ve got the code signing certificate created as shown above, you’ll need to move the certificate to the Trusted Root Certification Authorities. If you don’t, when you sign the powershell script, it still won’t be allowed to run (and the act of signing will produce an UnknownError).
Start the certificate manager (press Windows key, type cert, and select “Manage computer certificates“, or hit Windows+R, then type: “certmgr.msc“).
Expand Trusted Root Certification Authorities first, then expand Personal > Certificates and select the PowershellScripts Code Signing certificate and then drag it into the Trusted Certificates list as shown above (or you can right click, cut, and then paste it as well).
Now that you’ve got a trusted code signing cetificate, you can sign your Powershell scripts.
If you’ve only got one code signing certificate (which I presume you do otherwise you wouldn’t have needed a new one), from an administrative Powershell command prompt first switch directories to where the script you want to sign is located, then do these commands:
> $cert = (Get-ChildItem Cert:\LocalMachine\my -CodeSigningCert)[0]
> Set-AuthenticodeSignature .\reconnect-iscsi-targets.ps1 $cert
You should then see a table with the SignerCertificate, Status, and the Path. If everything went well, the Status should be Valid.
Here’s something interesting you can do with iSCSI targets and PowerShell using a signed PowerShell script.