Skip to content

Instantly share code, notes, and snippets.

@jpboyce
Created March 6, 2022 05:46
Show Gist options
  • Save jpboyce/b15c4760712af6d8969f0c30247b153d to your computer and use it in GitHub Desktop.
Save jpboyce/b15c4760712af6d8969f0c30247b153d to your computer and use it in GitHub Desktop.
name: 'Sign PowerShell Code'
trigger:
- main
variables:
- group: 'PowerShellCodeSigning'
pool:
vmImage: 'windows-latest'
steps:
- task: PowerShell@2
displayName: 'Import signing cert'
inputs:
targetType: inline
script: |
$secretBytes = [System.Convert]::FromBase64String("$(CodeSigning)")
$pfxcert = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2
$keyStoreFlags = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable `
-bxor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet `
-bxor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet
$pfxcert.Import($secretBytes, $null, $keyStoreFlags)
# import to personal store
$store = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store -ArgumentList @("My", "CurrentUser")
$store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$store.Add($pfxcert)
$store.Close()
- task: PowerShell@2
displayName: 'Sign PowerShell scripts'
inputs:
targetType: inline
script: |
$scriptFolder = "."
$scripts = Get-ChildItem -Path $scriptFolder -Filter "*.ps1" -Recurse -ErrorAction Stop
foreach ($script in $scripts) {
try {
# load cert
$codeSigningCert = Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert | Select-Object -First 1
Write-Output "Signing script `"$($script.Name)`" with certificate `"$($codeSigningCert.Thumbprint)`""
# sign script
$null = Set-AuthenticodeSignature -Certificate $codeSigningCert -FilePath $script.FullName -TimestampServer "http://timestamp.comodoca.com/rfc3161"
# copy to artifact staging location
$null = Copy-Item -Path $script.FullName -Destination $env:Build_ArtifactStagingDirectory
}
catch {
Write-Error $_
}
}
- task: PublishBuildArtifacts@1
inputs:
PathtoPublish: '$(Build.ArtifactStagingDirectory)'
ArtifactName: 'SignedScripts'
publishLocation: 'Container'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment