Hi, being SQL DBA there may be situations when you need to find out How many times SQL Service restarted. E.g. Let’s say there is an issue going on with a SQL Server and services got restarted. Your boss has asked you “Is it the first time it has happened? Can you tell me quickly the SQL Service restart history.
This is just one example, whatever may be the scenario, it is always good to have a PowerShell script handy.
The script counts the no. of SQL Server error logs and scan them for the text “SQL Server is starting”.
The output will have the complete message in the error log containing the text along with date and time of occurrence in server local time zone.
Script To Find How Many Times SQL Service Restarted:
#################################################################### # Objective: To Check how many times SQL Services got restarted # Author: Tridib Dev # Source:https://sqlgeekspro.com/ # Parameter: You need to provide SQL Instance Name #################################################################### # Define Input Parameter for SQL Instance Name param([parameter(Mandatory = $true)] $SQLInstanceName) Write-host 'SQL Service restart Details for: ' $SQLInstanceName Write-host '-----------------------------------------------------------' Write-host " " # Using SMO for Server Object creation $srv = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $SQLInstanceName # Loading sqlserver module Import-Module sqlserver -DisableNameCheck # Defining the connection string which helps in establishing connection from remote server $connection = "Data Source=$SQLInstanceName; Initial Catalog=master; Integrated Security=True; trustservercertificate=True;" # Get error log list $logs = Invoke-Sqlcmd -ConnectionString $connection -Query "EXEC xp_enumerrorlogs" # Count no. of Error logs $logCount = $logs.Count Write-Host "Number of SQL Server error logs: $logCount" foreach ($i in 0..$logCount) { # Call the ReadErrorLog method $logEntries = $srv.ReadErrorLog($i) # Filter and display results $logEntries | Where-Object { ($_.Text -match 'SQL Server is starting') } | Format-Table LogDate, ProcessInfo, Text -AutoSize }
Once you execute the script in PowerShell ISE, it will ask for the SQL Instance name for which you want to find the SQL Service restart history:

Example Result Set:
The output shows there are 100 SQL Error log files and the script has scanned them all. The SQL Service has restarted 3 times.
Hope it is is helpful. Please feel free to customize the script as per your requirements. Also you can use the same script to scan any other messages/errors by replacing the text.
Please leave a comment about your experience. You may also like to check the following interesting scripts.
Powershell Script to Validate SQL Servers
Powershell Script to Create Folders
List all permissions for a user in all or selective databases
Powershell Script to Create Folders

















