Blog |Follow Nick on Twitter| About
 

It's good practice to sign your powershell scripts, especially in an enterprise environment with an internal CA as it allows you to quickly identify internal code and if it's been modified. I've tweeted before that the process is a little cumbersome and have been meaning to post a little tip for making it easier.

I'm going to start from the point assuming you have had the cert issued to you by your admin, and it's already installed into your personal store, so you have something like this:

PS C:\Users\nick.bettison> Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert


   PSParentPath: Microsoft.PowerShell.Security\Certificate::CurrentUser\My

Thumbprint                                Subject
----------                                -------
1111111111111111111111111111111111111111  CN=Nick Bettison, OU=GROUP, OU=Users, OU=BLAH, OU=BLAH...



PS C:\Users\nick.bettison>

If you have multiple, take note of the one you want, the first one is [0], the 2nd is [1] and so on.

The process for signing a script (the long way) is:

$acert =(dir cert:\currentuser\My -CodeSigningCert)[0]
Set-AuthenticodeSignature ".\hello.ps1" -Certificate $acert

However, you can shorten this with a function in your profile. Powershell has a built in variable $profile, which is a predefined file path:

PS C:\Users\nick.bettison> write-host $profile
C:\Users\nick.bettison\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
PS C:\Users\nick.bettison>

Edit that file (create it, if it doesn't exist) and drop in the following quick little function:

function Sign-Script {
    $file = $args[0]
    $acert =(dir cert:\currentuser\My -CodeSigningCert)[0]
    Set-AuthenticodeSignature $file -Certificate $acert
}

(Remember the [0] from above, update -CodeSigningCert)[0] as appropriate for your cert store)

Save the file, and now you have Sign-Script shortcut, it's easy to use see the gif below 🙂

PowerShell Signing

 

 
Nick Bettison ©