How-To (CM-Self-Hosted): Database monitoring using scheduled task
121
Created On 11/12/26 15:36 PM - Last Modified 12/01/26 05:15 AM
Objective
This article covers how to monitor database connectivity from your Certificate Manager-Self-Hosted application node.
This process uses a scheduled task to run a PowerShell script that checks database connectivity from the host machine. The script connects to the SQL Server instance using Windows authentication and runs a simple query. Each check writes one row to a log file with a full timestamp, the user running the script, the result, and the response time.
Environment
25.1;25.3;26.1 TPP/TLSPDC TLSPDC
Procedure
- Reference the PowerShell script at the bottom of the article (See "Additional Information" section).
- Remote into the target application node.
- Create a new folder to store your script and logs.
- Install the script file to this new folder.
- Open the script file and edit the values in the "Configuration" section to match your environment.
- You can control the frequency at which the check is done by adjusting the "IntervalSeconds" variable. For example, setting this value to 5 will perform the check every 5 seconds.
- Designate a Windows Service account to launch this script; this account will need access to the database in order to test connectivity. You can use your existing service account if applicable.
- Open PowerShell ISE as the service account.
- Open the script file and run it.
- If the account can access the database and the database is online, we should see successful online entries being written to the console.
- If the service account cannot log into the sql instance, or the database is offline, then you will get failed offline entries.
- All these entries will also be written to the log file at the location specified in the script.
- Open Task Scheduler > Click on "Task Scheduler Library".
- Click "Create Task" > Name it "CMSH-sqlmonitor" > Change User or Group > Select the correct service account > Run whether user is logged on or not.
- Go to "Triggers" tab > New > Daily > Repeat task every 5 minutes > OK.
- Go to "Actions" tab > New > Program = powershell.exe > Add arguments = refer to example below > OK.
-
-File "C:\Users\shako1admin2\Desktop\Database Monitoring\Monitor-SqlConnectivity.ps1"
-
- Go to "Settings" tab > Set "If the task is already running, then the following rule applies" to "Stop the existing instance".
- Click OK to create the task, you will need to provide credentials for the service account.
- You may need to grant "Log on as a batch job" rights to the service account.
- Right-click on the new task > Run > Check the history tab to ensure it is launching successfully.
- Ensure the log file is being created.
- Use this command to tail the log:
-
Get-Content -Path "C:\Users\shako1admin2\Desktop\Database Monitoring\log.csv" -Wait -Tail 10
-
- Process complete.
Additional Information
<#
//-----------------------------------------------------------------------
// Monitor-SqlConnectivity.ps1
//
//
// This sample is provided "as is" without warranty of any kind.
//-----------------------------------------------------------------------
.SYNOPSIS
Checks SQL Server connectivity and appends the result to a CSV log.
.DESCRIPTION
Connects to the SQL Server instance using Windows authentication and runs a
simple query. Each check writes one row to a CSV log with a full timestamp,
the user running the script, the result, and the response time.
Edit the values in the CONFIGURATION section below before use.
#>
# ---------------------------- CONFIGURATION ----------------------------
$SqlServer = "ws2022-db01.tppshako.com" # SQL Server host name
$Port = 1433 # SQL Server TCP port
$LogPath = "C:\Users\shako1admin2\Desktop\Database Monitoring\log.csv" # CSV log file
$IntervalSeconds = 5 # Time between checks
$TimeoutSeconds = 5 # Connection timeout
$DurationMinutes = 5 # How long each run lasts; 0 = run continuously
# -----------------------------------------------------------------------
$connString = "Server=$SqlServer,$Port;Database=master;Integrated Security=SSPI;Connect Timeout=$TimeoutSeconds;Pooling=False"
$runAsUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
# Make sure the log folder exists
$logDir = Split-Path -Parent $LogPath
if (-not (Test-Path $logDir)) {
New-Item -ItemType Directory -Path $logDir -Force | Out-Null
}
$endTime = (Get-Date).AddMinutes($DurationMinutes)
while ($true) {
$cycleStart = Get-Date
$status = "ONLINE"
$errorMessage = ""
$conn = New-Object System.Data.SqlClient.SqlConnection $connString
$timer = [System.Diagnostics.Stopwatch]::StartNew()
try {
$conn.Open()
$cmd = $conn.CreateCommand()
$cmd.CommandText = "SELECT 1"
[void]$cmd.ExecuteScalar()
}
catch {
$status = "OFFLINE"
$errorMessage = $_.Exception.InnerException.Message
}
finally {
$timer.Stop()
$conn.Dispose()
}
$entry = [pscustomobject]@{
Timestamp = $cycleStart.ToString("yyyy-MM-dd HH:mm:ss.fff zzz")
User = $runAsUser
Server = $SqlServer
Status = $status
LatencyMs = $timer.ElapsedMilliseconds
Error = $errorMessage
}
$entry | Export-Csv -Path $LogPath -Append -NoTypeInformation
Write-Host "$($entry.Timestamp) $($entry.User) $($entry.Server) $($entry.Status) $($entry.LatencyMs)ms $($entry.Error)" -ForegroundColor Cyan
# Stop once the run duration is reached; 0 means run continuously
if ($DurationMinutes -gt 0 -and (Get-Date) -ge $endTime) { break }
# Wait for the rest of the interval before the next check
$remaining = $IntervalSeconds - ((Get-Date) - $cycleStart).TotalSeconds
if ($remaining -gt 0) { Start-Sleep -Seconds $remaining }
}