Windows Server - Caddy2 launcher script (scheduled task)

I’ve made changes to the script I showed and wanted to share the update. This PowerShell script can be created into a scheduled task and it will watch to see if Caddy is running and if not launches. Further it checks to see if any of the config files have been recently updated and if so perform a reload. Our environment uses multiple config files that are imported from the main Caddy file.

try {
    $Process = Get-Process caddy2 -ErrorAction Stop
    If($Process) {
        If($($(Get-Date) - $(Get-Item C:\Caddy\Caddyfile).LastWriteTime).TotalMinutes -le 5) {
            Start-Process -FilePath "C:\Caddy\caddy2.exe" -ArgumentList "reload -config C:\Caddy\Caddyfile"
            Write-Host "Caddy config file changed, reloaded config"
        }

        $ConfigFiles = Get-ChildItem C:\Caddy\configs
        ForEach($ConfigFile in $ConfigFiles) {
            If($($(Get-Date) - $($ConfigFile).LastWriteTime).TotalMinutes -le 5) {
                Start-Process -FilePath "C:\Caddy\caddy2.exe" -ArgumentList "reload -config C:\Caddy\Caddyfile"
                Write-Host "$($ConfigFile.Name) config file changed, reloaded config"
                Break
            }
        }
    }
}
catch {
    Start-Process -FilePath C:\Caddy\caddy2.exe -ArgumentList "start -config C:\Caddy\Caddyfile"
}
1 Like

No fix needed but hopefully this helps someone else.

This is also how I created the scheduled tasks. One runs every 6 minutes and the other runs at startup. We utlize gMSA accounts but you can change it to a normal account that has Admin access to the web server(s).

#Caddy Server Scheduled Task Setup
$action = New-ScheduledTaskAction -Execute "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-command `"& {C:\Scripts\CaddyWebServices\CaddyWebServices.ps1}`"" -WorkingDirectory "C:\Scripts\CaddyWebServices\"
$trigger = New-ScheduledTaskTrigger -At 05:00 -Once -RepetitionInterval (New-TimeSpan -Minutes 6) -RepetitionDuration ([timespan]::MaxValue)
$principal = New-ScheduledTaskPrincipal -UserID Domain\gMSAUser$ -LogonType Password -RunLevel Highest
Register-ScheduledTask CaddyWebServices -Action $action -Trigger $trigger -Principal $principal

$action = New-ScheduledTaskAction -Execute "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-command `"& {C:\Scripts\CaddyWebServices\CaddyWebServices.ps1}`"" -WorkingDirectory "C:\Scripts\CaddyWebServices\"
$trigger = New-ScheduledTaskTrigger -AtStartup
$principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask CaddyWebServicesOnStart –Action $action –Trigger $trigger –Principal $principal