Skip to content

Instantly share code, notes, and snippets.

@pcrockett
Last active May 3, 2023 19:10
Show Gist options
  • Save pcrockett/6bc1df46dd9fdf12a7377b323f9ec3a9 to your computer and use it in GitHub Desktop.
Save pcrockett/6bc1df46dd9fdf12a7377b323f9ec3a9 to your computer and use it in GitHub Desktop.
PowerShell script to cryptographically sign assemblies that's easy to use with a Continuous Integration server
$script:SignToolPath = "C:\Program Files (x86)\Windows Kits\8.1\bin\x64\signtool.exe"
$script:TimestampServers = "http://timestamp.comodoca.com/authenticode",
"http://timestamp.verisign.com/scripts/timestamp.dll",
"http://timestamp.digicert.com"
$script:TimestampServerIndex = 0
$script:MaxRetries = 7
$ErrorActionPreference = "Stop"
Set-StrictMode -Version 3.0
if (!$Args) {
throw "Please specify assemblies to sign by appending parameters."
}
function sign([string]$file) {
$server = $TimestampServers[$TimestampServerIndex]
$signToolArgs = @("sign", "/t", $server, "/v", $file)
& $SignToolPath $signToolArgs
$signResult = $LASTEXITCODE
if ($signResult -eq 1) {
# We had an error, probably with the timestamp server. Change which
# server we'll use for the next signing operation and notify the caller
# of the error.
$script:TimestampServerIndex++
if ($script:TimestampServerIndex -ge $TimestampServers.Count) {
$script:TimestampServerIndex = 0
}
throw "signtool exited with code $signResult"
}
elseif ($signResult -eq 2) {
Write-Warning "signtool exited with code $signResult"
}
}
for ($i = 0; $i -lt $Args.Count; $i++) {
for ($retryCount = 0; $retryCount -lt $MaxRetries; $retryCount++) {
try {
$output = sign $Args[$i]
# Sign was successful. Exit from the retry loop.
$output | Write-Host
break
}
catch {
if ($retryCount -eq $MaxRetries - 1) {
throw $_
}
}
# A failure happened. Will now allow the retry loop to continue.
Write-Host "Encountered a failure. Retrying... ($($retryCount + 1) of $MaxRetries)"
Start-Sleep -Seconds 5
}
if ($i -ne $Args.Count - 1) {
# We need to be kind to the timestamp server. Let's pause so we don't
# hammer it constantly.
Start-Sleep -Seconds 15
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment