How-To (CM-Self-Hosted): Database monitoring using scheduled task

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


  1. Reference the PowerShell script at the bottom of the article (See "Additional Information" section).
  2. Remote into the target application node.
  3. Create a new folder to store your script and logs.
  4. Install the script file to this new folder.
  5. Open the script file and edit the values in the "Configuration" section to match your environment.
  6. 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.
  7. 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.
  8. Open PowerShell ISE as the service account.
  9. Open the script file and run it.
  10. If the account can access the database and the database is online, we should see successful online entries being written to the console.
  11. If the service account cannot log into the sql instance, or the database is offline, then you will get failed offline entries.
  12. All these entries will also be written to the log file at the location specified in the script.
  13. Open Task Scheduler > Click on "Task Scheduler Library".
  14. Click "Create Task" > Name it "CMSH-sqlmonitor" > Change User or Group > Select the correct service account > Run whether user is logged on or not.
  15. Go to "Triggers" tab > New > Daily > Repeat task every 5 minutes > OK.
  16. Go to "Actions" tab > New > Program = powershell.exe > Add arguments = refer to example below > OK. 
    1. -File "C:\Users\shako1admin2\Desktop\Database Monitoring\Monitor-SqlConnectivity.ps1"
  17. Go to "Settings" tab > Set "If the task is already running, then the following rule applies" to "Stop the existing instance".
  18. Click OK to create the task, you will need to provide credentials for the service account.
  19. You may need to grant "Log on as a batch job" rights to the service account.
  20. Right-click on the new task > Run > Check the history tab to ensure it is launching successfully.
  21. Ensure the log file is being created.
  22. Use this command to tail the log:
    1. Get-Content -Path "C:\Users\shako1admin2\Desktop\Database Monitoring\log.csv" -Wait -Tail 10
  23. 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 }
}


Actions
  • Print
  • Copy Link

    https://knowledgebase.paloaltonetworks.com/KCSArticleDetail?id=kA1hj0000001l3JCAQ&lang=en_US&refURL=http%3A%2F%2Fknowledgebase.paloaltonetworks.com%2FKCSArticleDetail