Published on

May 6, 2015

How to Find When SQL Server was Started

Have you ever wondered how to find out when SQL Server was started? In this article, we will explore a simple script that can help you achieve this task.

Before we dive into the script, let’s discuss why you might need to know when SQL Server was started. One common reason is troubleshooting. When encountering issues with SQL Server, knowing the start time can provide valuable information for diagnosing the problem. Additionally, understanding the start time can help with performance analysis and capacity planning.

Now, let’s take a look at the script:

# Load Assemblies
[Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.Smo') | Out-Null
# Server object
$server = New-Object -TypeName "Microsoft.SqlServer.Management.Smo.Server" -ArgumentList $serverinstance
$searchCriteria = "Text like '%{0}%'" -f $stringToSearchFor
$SQLErrorLogs = $Server.EnumErrorLogs()
$SearchEntry = @()
ForEach ($SQLErrorLog in $SQLErrorLogs)
{
 $SearchResult = $server.ReadErrorLog($SQLErrorLog.ArchiveNo).select($searchCriteria) | Select-Object -Property LogDate, Text
 $SearchEntry = $SearchEntry + $searchResult
} 
$MeasureOccurences = $SearchEntry | Measure-Object -Property LogDate -Minimum -Maximum
$SQLSearchInfo = New-Object psobject -Property @{
 SearchText = $stringToSearchFor
 Occurances = $MeasureOccurences.Count
 MinDateOccurred = $MeasureOccurences.Minimum
 MaxDateOccurred = $MeasureOccurences.Maximum
 }
Write-Output $SQLSearchInfo | FT -AutoSize

This script utilizes the Microsoft.SqlServer.Smo assembly to interact with SQL Server. It reads the SQL Server error logs and searches for a specific text, in this case, “Starting up database ‘master'”. It then reports the number of times the string was found and displays the time of the last occurrence.

It’s important to note that the SQL Server error logs can get recycled, so this script may not always provide the exact start time. However, in most cases, it gives us a good indication.

You can customize the script by changing the search string and the default instance to match your environment. For example, you can modify it to search for specific error messages or events that you are interested in.

If you have used similar scripting capabilities to search your error logs, we would love to hear about your experiences. Feel free to share your scripts in the comments section so that others can benefit from your knowledge.

Scripting is a powerful tool in SQL Server administration and can greatly simplify various tasks. By learning scripting, you can enhance your skills and become more efficient in managing SQL Server instances.

Stay tuned for more SQL Server tips and tricks!

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.