Skip to content

Instantly share code, notes, and snippets.

@davidwallis3101
Last active January 13, 2020 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidwallis3101/2e079901c977ffa39a723e92dd606434 to your computer and use it in GitHub Desktop.
Save davidwallis3101/2e079901c977ffa39a723e92dd606434 to your computer and use it in GitHub Desktop.
Function Add-AuthenticodeSigningToScript {
<#
.SYNOPSIS
Signs scripts during the build process
.DESCRIPTION
Uses an in-memory cert to sign files, rather than from one of the stores
.PARAMETER Path
The file you want to sign
.EXAMPLE
C:\PS> Add-AuthenticodeSigningToScript c:\temp\test.ps1
.EXAMPLE
C:\PS> Get-ChildItem "c:\temp*.ps*" | Add-AuthenticodeSigningToScript -Certificate c:\test.pfx -Password (ConvertTo-SecureString "Testing!" -AsPlainText -Force)
.LINK
https://gist.github.com/davidwallis3101/2e079901c977ffa39a723e92dd606434
#>
[CmdletBinding(SupportsShouldProcess)]
Param (
[parameter(Mandatory, ValueFromPipeLine, ValueFromPipeLineByPropertyName)]
[ValidateNotNullOrEmpty()]
[Alias('FullName')]
[string[]]$Path,
[Parameter(Mandatory)]
[ValidateScript({
if(-Not ($_ | Test-Path) ){
throw "File does not exist"
}
if(-Not ($_ | Test-Path -PathType Leaf) ){
throw "The Path argument must be a file. Folder paths are not allowed."
}
return $true
})]
[System.IO.FileInfo]$Certificate,
[SecureString]$Password
)
Begin {
# TODO: - determine cert "intended puposes"
try {
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::New($Certificate, $Password)
}
catch {
throw
}
If ($cert.NotAfter -le (Get-Date)) {
Throw "Code signing certificate expired."
} Elseif ($cert.NotAfter -le (Get-Date).AddDays(30)) {
Write-Warning "Code signing certificate expires within the next 30 Days"
}
}
Process{
If (($Path | Get-AuthenticodeSignature).Status -eq 'NotSigned') {
If ($PSCmdlet.ShouldProcess($path)) {
$Null = $Path | Set-AuthenticodeSignature -Certificate $cert -ErrorAction Stop
}
} Else {
# TODO: Add support for force
Write-Verbose "$($Path) is already signed"
}
}
}
Get-ChildItem -Path c:\temp -Filter *.ps* -Include *.ps* -exclude *.tests.ps1 -Recurse |
Add-AuthenticodeSigningToScript `
-Certificate c:\temp\test.pfx `
-Password (ConvertTo-SecureString "Testing!" -AsPlainText -Force)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment