Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save magnuswatn/307316ac511f09b3fe031ff188070a7c to your computer and use it in GitHub Desktop.
Save magnuswatn/307316ac511f09b3fe031ff188070a7c to your computer and use it in GitHub Desktop.
Enable-AutomaticRebindOfRenewedCertificate
<#
Script that enables automatic rebinding of a renewed certificate in IIS.
Should create a scheduled task similar to the button in the IIS Manager.
Magnus Watn <[email protected]>
#>
$existingTask = (Get-ScheduledTask -TaskPath \Microsoft\Windows\CertificateServicesClient\ -TaskName IIS-AutoCertRebind -ErrorAction SilentlyContinue)
if ($null -ne $existingTask) {
Write-Host "Task already exists" -ForegroundColor Red
exit 1
}
$taskNamedValueClass = Get-CimClass -ClassName MSFT_TaskNamedValue -Namespace ROOT/Microsoft/Windows/TaskScheduler
$taskEventTriggerClass = Get-CimClass -ClassName MSFT_TaskEventTrigger -Namespace ROOT/Microsoft/Windows/TaskScheduler
$newCertValueQuery = New-CimInstance -CimClass $taskNamedValueClass -ClientOnly
$newCertValueQuery.Name = "NewCertHash"
$newCertValueQuery.Value = "Event/UserData/CertNotificationData/NewCertificateDetails/@Thumbprint"
$oldCertValueQuery = New-CimInstance -CimClass $taskNamedValueClass -ClientOnly
$oldCertValueQuery.Name = "OldCertHash"
$oldCertValueQuery.Value = "Event/UserData/CertNotificationData/OldCertificateDetails/@Thumbprint"
$trigger = New-CimInstance -CimClass $taskEventTriggerClass -ClientOnly
$trigger.Enabled = $true
$trigger.Subscription = "<QueryList><Query Id='0'><Select Path='Microsoft-Windows-CertificateServicesClient-Lifecycle-System/Operational'>*[System[EventID=1001]]</Select></Query></QueryList>"
$trigger.ValueQueries = $newCertValueQuery, $oldCertValueQuery
$action = New-ScheduledTaskAction -Argument 'renew binding /oldcert:$(OldCertHash) /newcert:$(NewCertHash)' -Execute '%SystemRoot%\System32\inetsrv\appcmd.exe'
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -ExecutionTimeLimit (New-TimeSpan -Hours 1) -MultipleInstances Queue -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 10)
$principal = New-ScheduledTaskPrincipal -Id "System" -RunLevel Highest -UserId "S-1-5-18"
$task = New-ScheduledTask -Trigger $trigger -Action $action -Principal $principal -Settings $settings
Register-ScheduledTask -TaskPath "\Microsoft\Windows\CertificateServicesClient\" -TaskName "IIS-AutoCertRebind" -InputObject $task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment