Skip to content

Instantly share code, notes, and snippets.

@Alex-Yates
Created September 10, 2021 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alex-Yates/fa6d9757e19f012519fc9fc7b2435eb2 to your computer and use it in GitHub Desktop.
Save Alex-Yates/fa6d9757e19f012519fc9fc7b2435eb2 to your computer and use it in GitHub Desktop.
Set-SqlDefaultPath.ps1
function Set-SqlDefaultPath {
param (
[Parameter(Mandatory=$true)][string]$SqlInstance,
$NewDefaultDataPath = "",
$NewDefaultLogPath = "",
$NewDefaultBackupPath = ""
)
try {
import-module dbatools
}
catch {
Write-Error "Failed to import dbatools (required): www.dbatools.io"
}
# The following SQL is copied from a combination of Thomas LeRock and MsSqlTips:
# https://thomaslarock.com/2017/06/changing-default-database-file-locations-in-sql-server-2016/
# https://www.mssqltips.com/sqlservertip/1583/changing-the-default-sql-server-backup-folder/
$setDefaultDataPathSql = @"
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE'
, N'Software\Microsoft\MSSQLServer\MSSQLServer'
, N'DefaultData'
, REG_SZ
, N'$NewDefaultDataPath'
GO
"@
$setDefaultLogPathSql = @"
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE'
, N'Software\Microsoft\MSSQLServer\MSSQLServer'
, N'DefaultLog'
, REG_SZ
, N'$NewDefaultLogPath'
GO
"@
$setDefaultBackupPathSql = @"
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE'
, N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer'
, N'BackupDirectory'
, REG_SZ
, N'$NewDefaultBackupPath'
"@
if ($NewDefaultDataPath -notlike ""){
Invoke-DbaQuery -SqlInstance $SqlInstance -Query $setDefaultDataPathSql
}
if ($NewDefaultLogPath -notlike ""){
Invoke-DbaQuery -SqlInstance $SqlInstance -Query $setDefaultLogPathSql
}
if ($NewDefaultBackupPath -notlike ""){
Invoke-DbaQuery -SqlInstance $SqlInstance -Query $setDefaultBackupPathSql
}
return "Restart required"
}
<#
Tutorial part 1:
Get the current default paths by running the following (requires dbatools)
Get-DbaDefaultPath $SqlInstance
Tutorial part 2:
Change the default paths using the following. (Note, updating the data path sometimes updates the log path too, not sure why):
$SqlInstance = "localhost"
$NewDefaultDataPath = ""
$NewDefaultLogPath = ""
$NewDefaultBackupPath = ""
Set-SqlDefaultPath -SqlInstance $SqlInstance -NewDefaultDataPath $NewDefaultDataPath -NewDefaultLogPath $NewDefaultLogPath -NewDefaultBackupPath $NewDefaultBackupPath
Tutorial part 3:
Repeat tutorial part 1. Observe there has been no change to the default paths. Then restart the SQL Server instance and check the paths again. They should now have updated.
Note: Existing database files will not be moved to the new paths. These changes will only take effect for new databases.
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment