Signing your Powershell scripts

Once you write a script in Powershell, you have to sign the saved .ps1 file before you can execute it on other domain computers.  This is a security precaution put into place to help prevent unauthorized code execution if someone nefarious modifies your saved scripts.  While this sounds like an inconvenience, it doesn’t really require that much additional effort on your part once you’ve set it up.  Like many other things, there are several ways to accomplish this, and I’ll discuss two of them.

 

First, there’s a one-liner command that you can execute in an interactive Powershell session.  You’ll have to copy and paste this command into the Powershell console, and then edit the name of the file you want to sign to point to your file.  In this example, the file to be signed is c:\myscript.ps1

[powershell]PS C:\> Set-AuthenticodeSignature c:\myscript.ps1 @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0] -TimestampServer “http://timestamp.verisign.com/scripts/timstamp.dll”[/powershell]

In case you’re wondering, that -TimestampServer option will include the date and time that you sign the script in the signature, and in the future, Powershell clients will check that date and time against your signature to verify that the certificate was valid at the time that it was signed.  Compare this to not using that option, where if you try to run the script after your certificate expires, it will refuse to run until you re-sign the file with a currently-valid certificate.

 

However, if you want a little more flexibility, you can create a script to sign your files.  If you take the script below and save it to a file, such as add-signature.ps1, you can double-click on it in the Explorer shell and it will prompt you for the name of the file that you want to sign.

[powershell]param([string] $file=$(throw “Please specify a filename.”))
$cert = @(Get-ChildItem cert:\CurrentUser\My -codesigning)[0] Set-AuthenticodeSignature $file $cert -TimestampServer “http://timestamp.verisign.com/scripts/timstamp.dll”[/powershell]

Don’t forget that you have to sign this script in order for it to work!  For that, you can use the one-liner above.  Or, if you want to import my (agerber.admin) code-signing certificate into your trusted publisher’s list, you can simply download this file and you’ll be all set!

If you want to know more, we have additional documentation written up about code signing and certificates.