The script signOfficeDocument.ps1 signs Word, Excel and PowerPoint documents (.docx, .xlsx, .pptx) from Windows PowerShell 5.1, with the signature that Office 2010 and later create and show. Microsoft Office is not needed. With -SignatureLine the signature is visible on a signature line of a Word document.
How to run it
powershell -ExecutionPolicy Bypass -File signOfficeDocument.ps1 test.docx test[signed].docx
powershell -ExecutionPolicy Bypass -File signOfficeDocument.ps1 test.docx -SignatureLine -SuggestedSigner "John Smith" -Comments "Approved"
powershell -ExecutionPolicy Bypass -File signOfficeDocument.ps1 report.xlsx -Level XadesLT -TimestampUrl https://ca.signfiles.com/TSAServer.aspx
Options: -Level (XadesB, XadesT, XadesLT), -Comments, -SignerRole, -SignatureLine, -SuggestedSigner, -TimestampUrl, and the certificate options.
The signing code of the script
Initialize-SignLib
if (-not $OutputFile) { $OutputFile = Get-DefaultOutputFile $InputFile }
$sign = New-Object SignLib.OfficeSignature (Get-SerialNumber $SerialNumber)
$sign.DigitalSignatureCertificate = Get-SigningCertificate -PfxFile $PfxFile -PfxPassword $PfxPassword -Thumbprint $Thumbprint -LocalMachine:$LocalMachine
$sign.SignatureStandard = [System.Enum]::Parse([SignLib.Xml.XadesSignatureStandard], $Level)
$sign.HashAlgorithm = Get-HashAlgorithm $HashAlgorithm
if ($Comments) { $sign.SignatureComments = $Comments }
if ($SignerRole) { $sign.SignerRole = $SignerRole }
if ($TimestampUrl) { $sign.TimeStamping.ServerUrl = [Uri]$TimestampUrl }
if (($Level -ne 'XadesB') -and (-not $TimestampUrl)) { throw "The level $Level needs a time-stamping server (-TimestampUrl)." }
if ($SignatureLine)
{
# The first unsigned signature line of the Word document; a new line at the end of the document when there is none.
$line = New-Object SignLib.Office.OfficeSignatureLine
$line.Placement = [SignLib.Office.OfficeSignatureLinePlacement]::UseExistingOrAddNew
$line.ShowSignDate = $true
if ($SuggestedSigner) { $line.SuggestedSigner = $SuggestedSigner }
$sign.SignatureLine = $line
}
Write-Host "Perform the digital signature ($Level)..."
Set-SmartCardPin $SmartCardPin
$sign.ApplyDigitalSignature((Get-FullPath $InputFile), (Get-FullPath $OutputFile))
Write-Host "Signed file: $OutputFile"
Run the full sample. The script signOfficeDocument.ps1 is in the folder PowerShell Scripts of the library download, with SignLib.dll, a test certificate and test documents. It runs in Windows PowerShell 5.1. Without a serial number the library runs in demo mode. Download the library and the samples · User manual
Frequently asked questions
Can I sign all the Office documents of a folder?
Yes, with signFolder.ps1 of the same folder and -Format Office.