Sign PowerShell Scripts

If you’ve been to any of my PowerShell sessions or classes you know I often recommend using an AllSigned execution policy for your production servers. Assuming you’ve gone ahead and installed a code signing certificate on your desktop, how do you go about signing all your scripts. Here’s how you might sign all your scripts in a given directory.

#assumes one code signing cert
PS C:\> $cert=Get-ChildItem -FilePath cert:\CurrentUser\my -CodeSigningCert
PS C:\> New-Alias sign Set-AuthenticodeSignature
PS C:\> dir c:\scripts\*.ps1 | foreach {sign $_ $cert}

If you had a text list with a full path and file to each script you could do something like this:

PS C:\> get-content c:\scripts.txt | foreach {sign $_ $cert}

If you have PrimalScript, you can configure it to sign scripts automatically everytime you save a PowerShell file. Again, assuming you only have a single code signing certificate installed, go to to Tools – Options and navigate to ScriptSettings – Security. In the PowerShell Security section you should see your execution policy. Leave the certificate field blank and check the box for "Automatically sign scripts when saving"

codesigning

Now whenever you save a PowerShell script it will automatically be signed. If you prefer, you can leave the box unchecked and manually sign your scripts from the Script menu.

Currently Primalscript will use the first code signing certificate it finds. We’re still trying to find a good mechanism for allowing you to choose a specific code signing certificate. Right now it appears the best solution if you have multiple certificates is to export your certificate to a PFX file and then use the browse button next to the certificate field to load the file.