Last active
January 13, 2020 15:02
-
-
Save davidwallis3101/2e079901c977ffa39a723e92dd606434 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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