I remember a while back being asked about a way to fetch the Default Data and Log path for a SQL Server instance. This information is present in the registry keys and the keys are created only if you modify the default paths to a path other than the SQLDataRoot path using which the SQL instance was installed.
So I thought I would put together a quick post to fetch this information using a Powershell script. The function takes in the instance name as the parameter value. Note that for a default instance, the instance name is MSSQLServer.
############################################################
# Author: Amit Banerjee
# Information: Finds out default data and log file paths for a given SQL Server instance
############################################################
Function fnGetDefaultDBLocation
{
Param ([string] $vInstance)
# Get the registry key associated with the Instance Name
$vRegInst = (Get-ItemProperty -Path HKLM:"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL" -ErrorAction SilentlyContinue).$vInstance
$vRegPath = "SOFTWARE\Microsoft\Microsoft SQL Server\" + $vRegInst + "\MSSQLServer"
# Get the Data and Log file paths if available
$vDataPath = (Get-ItemProperty -Path HKLM:$vRegPath -ErrorAction SilentlyContinue).DefaultData
$vLogPath = (Get-ItemProperty -Path HKLM:$vRegPath -ErrorAction SilentlyContinue).DefaultLog
# Report the entries found
if ($vDataPath.Length -lt 1)
{
$vRegPath = "SOFTWARE\Microsoft\Microsoft SQL Server\" + $vRegInst + "\Setup"
$vDataPath = (Get-ItemProperty -Path HKLM:$vRegPath -ErrorAction SilentlyContinue).SQLDataRoot + "\Data\"
Write-Host "Default Data Path: " $vDataPath
}
else
{
Write-Host "Default Data Path:" $vDataPath
}
if ($vLogPath.Length -lt 1)
{
$vRegPath = "SOFTWARE\Microsoft\Microsoft SQL Server\" + $vRegInst + "\Setup"
$vDataPath = (Get-ItemProperty -Path HKLM:$vRegPath -ErrorAction SilentlyContinue).SQLDataRoot + "\Data\"
Write-Host "Default Log Path: " $vDataPath
}
else
{
Write-Host "Default Log Path:" $vLogPath
}
}
fnGetDefaultDBLocation "MSSQLServer"
Nice script. Up to SQL 2005 I’ve used xp_regread (which I know is undocumented) and Powershell , but since 2008 I’vw used SQLCLR
LikeLike
Yes. xp_regread would serve the same purpose but I try and avoid xp_regread as much as possible! 🙂
LikeLike
Worked perfectly – Thank you Amit !!
LikeLike