When creating PowerShell scripts, modules, and profiles, it is considered best practice to digitally sign them. Signing scripts performs the following two functions:
Ensures the script is from a trusted source
Ensures the script hasn't been altered since it was signed
Getting ready
To sign a PowerShell script, a code-signing certificate will be needed. Normally these certificates will be provided by your enterprise Private Key Infrastructure (PKI), and the PKI Administrator should be able to help you with the requesting process. Code-signing certificates can also be purchased from third party Certificate Authorities (CA) which can be helpful if your scripts are being distributed outside of your corporate environment.
Once received, the code-signing cert should be added to your Current User | Personal | Certificates certificate store on your computer. Additionally, the root certificate from the Certificate Authority should be added to the Trusted Publishers store for all computers that are going to execute the signed scripts.
The signing process is fairly simple, but also extremely powerful. The process starts by searching the Current User certificate store for a certificate capable of code signing and is placed into a $cert variable. Set-AuthenticodeSignature is then called to sign the script with the certificate.
If there is more than one code signing certificate on your system, you need to select which certificate to use. To achieve this, update the first line to include a where clause. For example:
If you open the script in a text editor after it has been signed, you will notice several lines of content appended to the end. These additional lines are the signature that PowerShell will verify before running the script.
Note
Any change to the script (even adding or removing a space) will invalidate the signature. Once the script has been signed, if you need to make changes, you must repeat the signing process.
Executing this script will create the certificate and install it on the local computer as shown in the following screenshot:
Note
The self-signed certificate still needs to be added to your Trusted Root Certification Authorities and Trusted Publishers store for the certificate to be considered valid by client computers.