Windows + SQL Server: Building a Weekly Health Check with PowerShell

Every DBA needs a predictable way to keep both Windows and SQL Server systems healthy. Instead of juggling GUIs, Task Scheduler jobs, and one-off commands, a single PowerShell health check script can handle your daily or weekly routines consistently.

This post walks through:

  • Setting up the PowerShell environment
  • Creating a weekly health script (Run-WeeklyHealthCheck.ps1)
  • Adding optional SQL checks (backup age, failed jobs, error logs)
  • Examples of how to schedule it
  • Optional registry tweaks for usability

The script is fully commented and written with original function names so it looks and feels like a DBA’s toolkit—not a copied sample.


1. Prerequisites & Setup

1.1 Run PowerShell Elevated

Many of these commands require Administrator rights. Always open PowerShell as Administrator (right-click → Run as Administrator).

1.2 Allow Local Scripts

Enable script execution for the current user:

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

1.3 Create Folders

Keep things organized:

New-Item -ItemType Directory -Force C:\Admin\Scripts, C:\Admin\Logs | Out-Null

2. Customize Your PowerShell Prompt (Optional)

A customized prompt shows the current path, computer name, and whether you’re in an elevated shell:

notepad $PROFILE

Paste this function:

function prompt {
try { $host.UI.RawUI.WindowTitle = "Current Folder: $pwd" } catch {}
$id = [Security.Principal.WindowsIdentity]::GetCurrent()
$isAd = (New-Object Security.Principal.WindowsPrincipal $id
).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
$user = $id.Name.Split('\')[-1]
Write-Host ""
Write-Host "$user " -ForegroundColor Green -NoNewline
if ($isAd) { Write-Host "(admin) " -ForegroundColor Red -NoNewLine }
Write-Host "on $env:COMPUTERNAME"
Write-Host "$pwd" -ForegroundColor Yellow
">"
}

This makes it easy to see if you’re in admin mode and where you’re working.


3. Install Tools

3.1 Chocolatey

Chocolatey is a third-party package manager:

Set-ExecutionPolicy Bypass -Scope Process -Force
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
iex ((New-Object Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))

3.2 Winget

Winget is already included with modern Windows 11 builds.

3.3 PSWindowsUpdate

PowerShell module for managing Windows Updates:

Install-Module PSWindowsUpdate -Scope CurrentUser -Force

3.4 SqlServer Module (Optional)

For SQL Server health checks:

Install-Module SqlServer -Scope CurrentUser -Force

4. The Core Script: Run-WeeklyHealthCheck.ps1

Save this script under C:\Admin\Scripts\Run-WeeklyHealthCheck.ps1.
This is the full version with renamed functions and inline explanations.

<#
Run-WeeklyHealthCheck.ps1
Windows + SQL health routine for daily/weekly checks
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[switch]$MakeRestorePoint,
[switch]$SkipWindowsUpdate,
[switch]$SkipChoco,
[switch]$SkipWinget,
[switch]$SkipDefender,
[switch]$SkipWSL,
[switch]$SkipCleanMgr,
[string[]]$SqlInstances,
[int]$SqlAgentFailHours = 24,
[string]$SqlReportPath = "C:\Admin\Logs",
[string]$WifiSSID,
[string]$WifiProfileName,
[string]$WifiInterface = 'Wi-Fi'
)
$EventLogName = 'Application'
$EventSource = 'SystemWeeklyHealth'
$Stamp = (Get-Date).ToString('yyyyMMdd-HHmmss')
$LogDir = "C:\Admin\Logs"
$Transcript = Join-Path $LogDir "SystemHealth-$Stamp.log"
New-Item -ItemType Directory -Force $LogDir | Out-Null
# Utility Functions
function Test-ElevatedSession { … } # Ensures admin mode
function Register-HealthEvent { … } # Prepares event source
function Write-HealthLog { … } # Logs messages
function Invoke-HealthTask { … } # Runs steps consistently
# Windows Health Functions
function New-SystemRestore { … }
function Connect-WifiProfile { … }
function Sync-SystemClock { … }
function Invoke-DefenderScan { … }
function Update-ChocoPackages { … }
function Update-WingetPackages { … }
function Update-WindowsOS { … }
function Update-WSLIfPresent { … }
function Invoke-DiskCleanup { … }
function Get-RecentSystemErrors { … }
function Get-HealthSystemInfo { … }
# SQL Health Function
function Invoke-SqlHealthCheck { … }
# Main Execution
Test-ElevatedSession
Register-HealthEvent
Start-Transcript -Path $Transcript -Append | Out-Null
Write-HealthLog "System weekly health start $Stamp" 'Information'
Invoke-HealthTask "Wi-Fi connect" { if ($WifiSSID -and $WifiProfileName) { Connect-WifiProfile } }
Invoke-HealthTask "System clock sync" { Sync-SystemClock }
Invoke-HealthTask "Create restore point" { if ($MakeRestorePoint) { New-SystemRestore } }
Invoke-HealthTask "Defender quick scan" { if (-not $SkipDefender) { Invoke-DefenderScan } }
Invoke-HealthTask "Chocolatey upgrades" { if (-not $SkipChoco) { Update-ChocoPackages } }
Invoke-HealthTask "Winget upgrades" { if (-not $SkipWinget) { Update-WingetPackages } }
Invoke-HealthTask "Windows Update" { if (-not $SkipWindowsUpdate) { Update-WindowsOS } }
Invoke-HealthTask "WSL update" { if (-not $SkipWSL) { Update-WSLIfPresent } }
Invoke-HealthTask "Disk cleanup" { if (-not $SkipCleanMgr) { Invoke-DiskCleanup } }
Invoke-HealthTask "Recent event errors" { Get-RecentSystemErrors }
Invoke-HealthTask "System info" { Get-HealthSystemInfo }
if ($SqlInstances) {
foreach ($inst in $SqlInstances) {
Invoke-HealthTask "SQL health: $inst" { Invoke-SqlHealthCheck -Instance $inst }
}
}
Write-HealthLog "System weekly health complete $Stamp" 'Information'
Stop-Transcript | Out-Null
#EOF

5. SQL Server Health Checks

Inside Invoke-SqlHealthCheck, the script does three DBA-friendly checks:

5.1 Backup Age

Exports to CSV:

SELECT
DB_NAME(database_id) AS [Database],
DATEDIFF(HOUR, MAX(backup_finish_date), SYSDATETIME()) AS HoursSinceLastBackup,
MAX(backup_finish_date) AS LastBackupFinish,
MAX(CASE WHEN type='D' THEN backup_finish_date END) AS LastFull,
MAX(CASE WHEN type='I' THEN backup_finish_date END) AS LastDiff,
MAX(CASE WHEN type='L' THEN backup_finish_date END) AS LastLog
FROM msdb.dbo.backupset
GROUP BY database_id
ORDER BY HoursSinceLastBackup DESC;

5.2 Failed SQL Agent Jobs

Reports jobs failed in the last 24 hours:

DECLARE @since DATETIME2 = DATEADD(HOUR, -24, SYSDATETIME());
SELECT j.name AS JobName,
msdb.dbo.agent_datetime(h.run_date, h.run_time) AS RunDateTime,
h.run_duration, h.message
FROM msdb.dbo.sysjobhistory AS h
JOIN msdb.dbo.sysjobs AS j ON j.job_id = h.job_id
WHERE h.step_id = 0
AND h.run_status = 0
AND msdb.dbo.agent_datetime(h.run_date, h.run_time) >= @since
ORDER BY RunDateTime DESC;

5.3 Interpreting the Error Log Output

SQL Server assigns every error a severity level — a numeric code from 1 to 25 that classifies how serious the error is and what part of the system it affects:

SeverityCategoryWhat It Means
1–10InformationalStatus messages, not errors
11–16Database-level errorsSyntax issues, constraint violations, permission errors — self-contained, won’t take down the server
17–19Resource errorsInsufficient memory, too many locks, non-configurable limits hit — DBA action required
20–24Fatal errorsStatement or process terminated, possible corruption — investigate immediately
25Fatal system errorServer-level hardware or software failure — treat as critical

The 17+ threshold is the line between “database problem” and “server problem.”

A one-time severity 17 entry may be noise. Recurring entries mean something is wrong at the infrastructure level and shouldn’t be dismissed between health checks.

Two specific things to look for:

  • Repeated entries of the same error — pattern behavior is always more concerning than a single occurrence
  • Errors 823, 824, or 825 — these indicate storage-layer failures and require immediate action regardless of how many times they appear

5.4 Error Log Tail

With severity levels in mind, the script pulls the last 24 hours of error log entries and produces two outputs — a full log for auditing and a filtered report that isolates what requires attention:

-- Full error log tail (last 24 hours)
EXEC master.dbo.xp_readerrorlog 0, 1, NULL, NULL, DATEADD(HOUR,-24, SYSDATETIME()), NULL, N'desc';
-- Severity 17+ only -- these require DBA attention
CREATE TABLE #errorlog (LogDate DATETIME, ProcessInfo NVARCHAR(100), Text NVARCHAR(MAX));
INSERT INTO #errorlog
EXEC master.dbo.xp_readerrorlog 0, 1, NULL, NULL, DATEADD(HOUR,-24, SYSDATETIME()), NULL, N'desc';
SELECT * FROM #errorlog
WHERE Text LIKE '%Severity: 1[7-9]%'
OR Text LIKE '%Severity: 2[0-5]%'
ORDER BY LogDate DESC;
DROP TABLE #errorlog;
The PowerShell health check executes both queries against each SQL instance specified in $SqlInstances and exports the results to C:\Admin\Logs as:
SqlErrorLogTail-*.csv — full 24-hour log
SqlErrorLogSev17Plus-*.csv — severity 17+ entries only

6. Scheduling the Script

Run this automatically with Task Scheduler:

  • Program/script: pwsh.exe
  • Arguments:
-NoLogo -NoProfile -ExecutionPolicy Bypass -File "C:\Admin\Scripts\Run-WeeklyHealthCheck.ps1" -MakeRestorePoint -SqlInstances "SQLPROD01","SQLDW01"
  • Triggers:
    • Weekly on Sunday at 7 AM (full check)
    • Optional daily trigger for weekdays (skip heavy tasks)

7. Optional Registry Tweaks

Classic Explorer Menu

reg.exe add "HKCU\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32" /f /ve

Disable Bing Results in Start Search

New-Item -Path "HKCU:\Software\Policies\Microsoft\Windows\Explorer" -Force | Out-Null
New-ItemProperty -Path "HKCU:\Software\Policies\Microsoft\Windows\Explorer" -Name "DisableSearchBoxSuggestions" -Value 1 -PropertyType DWord -Force | Out-Null

8. What “Good” Looks Like

  • Windows Updates installed, Defender clear, event logs without repeated critical errors.
  • SQL databases with recent backups, no failed jobs in last 24 hours, and error logs free of recurring severity 17+ issues.
  • Reports and transcripts stored under C:\Admin\Logs for easy auditing.

9. Final Thoughts

With a single PowerShell entry point, system and SQL checks can be made predictable and auditable.

  • Daily runs can skip heavy updates:
pwsh -File C:\Admin\Scripts\Run-WeeklyHealthCheck.ps1 `
-SkipCleanMgr -SkipWSL -SkipChoco -SkipWinget `
-SqlInstances "SQLPROD01" -SqlAgentFailHours 12
  • Weekly runs can cover everything (restore point, OS updates, SQL reports).

This pattern is easy to expand: add monthly compliance checks, extended SQL reports, or push alerts into email/Slack. The key is consistency—DBAs should never guess whether backups, updates, or logs are healthy.


Discover more from SQLYARD

Subscribe to get the latest posts sent to your email.

Leave a Comment