You may have noticed by now that the default for SharePoint PowerShell is to change the restrictions on running PowerShell scripts to use AllSigned. A good explaination of “Why” is here on Lee Holmes’s blog, but this leaves you needing to sign your own scripts in order to run them. Don’t worry--it’s not as complicated as it sounds! Let’s look at how to do this in an easy way (especially for those of you without a real “Cert” of your own).
ONE TIME STEPS -- This portion of the walkthrough only needs to be done once (note that i'll post later on how to use this same cert on multiple machines):
First we need to create a cert. You can do this on any machine—it requires makecert.exe which is part of the Microsoft Windows Platform SDK. Once you install the SDK you can find MakeCert (you can run this command from “Program Files” to find the exe: ls -Recurse -Filter "makecert.exe").
For a full walkthrough see Scott Hanselman’s post, but in short, we can create a local certificate authority for your computer by running this command in PowerShell from the folder that contains Makecert.exe:
./makecert.exe -n "CN=PowerShell Local Certificate Root" -a sha1 -eku 18.104.22.168.22.214.171.124.3 -r -sv root.pvk root.cer -ss Root -sr localMachine
You’ll be prompted for a private key—provide one you’ll remember (or write it down!):
Then you are prompted to enter the key you just created.
This has created a certificate authority (if you have issues see Scott’s Post). Now we can create a personal Certificate using our new Cert Authority by running this command from the same folder (you’ll be prompted for the same key as above):
./makecert.exe -pe -n "CN=PowerShell User" -ss MY -a sha1 -eku 126.96.36.199.188.8.131.52.3 -iv root.pvk -ic root.cer
You can make sure the certificate was properly generated using this command:
Get-ChildItem cert:\CurrentUser\My –codesign
You can now delete the two temporary files root.pvk and root.cer in your working directory. The certificate info is stored with that of others, in "C:\Documents and Settings\<your username>\Application Data\Microsoft\SystemCertificates\My\".
Now—the above steps only need to be done once as we can use this cert to sign all our scripts. To Sign a script, simply point the following command to your script.
Set-AuthenticodeSignature “c:\foo.ps1” @(Get-ChildItem cert:\CurrentUser\My -codesigning)
Here’s a function I use (it’s in my profile.ps1 file) to sign my scripts:
Set-AuthenticodeSignature $file @(Get-ChildItem cert:\CurrentUser\My -codesigning)
Note: the first time you run your own “untrusted” script you’ll get this prompt below—just say “Always Run” to avoid seeing it in the future.