By default, PowerShell scripts are restricted from running for security reasons. While the -ExecutionPolicy Bypass switch can override this restriction, it's not the most secure option. If you want to enhance security, it's worth exploring how to allow only signed scripts to run. Here, we'll look at how to create and authorize only signed scripts.
To sign our scripts, we need a certificate. Here's how to create a self-signed certificate.
PS C:\Users\Administrator\Desktop> $CertificateName = "STD Certificate"
PS C:\Users\Administrator\Desktop> $OutPutPFXFilePath = "C:\Users\administrator\Desktop\MyNewSigningCertificate.pfx"
PS C:\Users\Administrator\Desktop> $MyStrongPassword = ConvertTo-SecureString -String "MyPassword" -Force -AsPlainText
PS C:\Users\Administrator\Desktop> New-SelfSignedCertificate -subject $CertificateName -Type CodeSigning -NotAfter (Get-Date).AddYears(10) -KeyLength 4096 | Export-PfxCertificate -FilePath $OutPutPFXFilePath -password $MyStrongPassword
PS C:\Users\Administrator\Desktop> $MyCertFromPfx = Get-PfxCertificate -FilePath 'C:\Users\administrator\Desktop\MyNewSigningCertificate.pfx'
Enter password : ********
PS C:\Users\Administrator\Desktop> Set-AuthenticodeSignature -PSPath 'C:\Users\administrator\Desktop\script.ps1' -Certificate $MyCertFromPfx
To be correctly recognized, a self-signed certificate must be imported on the computers on which we want to run the PowerShell scripts. Type the following commands with administrator rights.
PS C:\Users\Administrator\Desktop> $MyStrongPassword = ConvertTo-SecureString -String "MyPassword" -Force -AsPlainText
PS C:\Users\Administrator\Desktop> $CertPath = "C:\Users\administrator\Desktop\MyNewSigningCertificate.pfx"
PS C:\Users\Administrator\Desktop> Import-PfxCertificate -FilePath $CertPath "cert:\LocalMachine\Root" -Password $MyStrongPassword
PS C:\Users\Administrator\Desktop> Import-PfxCertificate -FilePath $CertPath "cert:\LocalMachine\TrustedPublisher" -Password $MyStrongPassword
PS C:\Users\Administrator\Desktop> Get-AuthenticodeSignature 'C:\Users\administrator\Desktop\script.ps1'
Contact :