Problem
You want to sign a PowerShell script so that it may be run on systems that have their execution policy set to require signed scripts.
Solution
To sign the script with your standard codesigning certificate, use the SetAuthenticodeSignature cmdlet:
$cert = @(GetChildItem cert:\CurrentUser\My CodeSigning)[0] SetAuthenticodeSignature file.ps1 $cert
Alternatively, you may also use other traditional applications (such as signtool.exe) to sign PowerShell .ps1 and .ps1xml files.
Discussion
Signing a script or formatting file provides you and your customers with two primary benefits: publisher identification and file integrity. When you sign a script or formatting file, PowerShell appends your digital signature to the end of that file. This signature verifies that the file came from you and also ensures that nobody can tamper with the content in the file without detection. If you try to load a file that has been tampered with, PowerShell provides the following error message:
File C:\temp\test.ps1 cannot be loaded. The contents of file C:\temp\test.ps1 may have been tampered because the hash of the file does not match the hash stored in the digital signature. The script will not execute on the system. Please see "gethelp about_signing" for more details.. At line:1 char:10
+ .\test.ps1 <<<<
When it comes to the signing of scripts and formatting files, PowerShell participates in the standard Windows Authenticode infrastructure. Because of that, techniques you may already know for signing files and working with their signatures continue to work with PowerShell scripts and formatting files. While the SetAuthenticodeSignature cmdlet is primarily designed to support scripts and formatting files, it also supports DLLs and other standard Windows executable file types.
To sign a file, the SetAuthenticodeSignature cmdlet requires that you provide it with a valid codesigning certificate. Most certification authorities provide Authenticode codesigning certificates for a fee. By using an Authenticode codesigning certificate from a reputable certification authority (such as VeriSign or Thawte), you can be sure that all users will be able to verify the signature on your script. Some online services offer extremely cheap codesigning certificates, but be aware that many machines may be unable to verify the digital signatures created by those certificates.
You can still gain many of the benefits of code signing on your own computers by generating your own codesigning certificate. While other computers will not be able to recognize the signature, it still provides tamperprotection on your own computer.
The –TimeStampServer parameter lets you sign your script or formatting file in a way that makes the signature on your script or formatting file valid even after your codesigning certificate expires.
For more information about the SetAuthenticodeSignature cmdlet, type GetHelp SetAuthenticodeSignature.