forked from dataplat/dbatools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGet-SqlDefaultPaths.ps1
53 lines (49 loc) · 1.49 KB
/
Get-SqlDefaultPaths.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
Function Get-SqlDefaultPaths
{
<#
.SYNOPSIS
Internal function. Returns the default data and log paths for SQL Server. Needed because SMO's server.defaultpath is sometimes null.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[Alias("ServerInstance", "SqlInstance")]
[object]$SqlServer,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string]$filetype,
[System.Management.Automation.PSCredential]$SqlCredential
)
$server = Connect-SqlServer -SqlServer $SqlServer -SqlCredential $SqlCredential
switch ($filetype) { "mdf" { $filetype = "data" } "ldf" { $filetype = "log" } }
if ($filetype -eq "log")
{
# First attempt
$filepath = $server.DefaultLog
# Second attempt
if ($filepath.Length -eq 0) { $filepath = $server.Information.MasterDbLogPath }
# Third attempt
if ($filepath.Length -eq 0)
{
$sql = "select SERVERPROPERTY('InstanceDefaultLogPath') as physical_name"
$filepath = $server.ConnectionContext.ExecuteScalar($sql)
}
}
else
{
# First attempt
$filepath = $server.DefaultFile
# Second attempt
if ($filepath.Length -eq 0) { $filepath = $server.Information.MasterDbPath }
# Third attempt
if ($filepath.Length -eq 0)
{
$sql = "select SERVERPROPERTY('InstanceDefaultDataPath') as physical_name"
$filepath = $server.ConnectionContext.ExecuteScalar($sql)
}
}
if ($filepath.Length -eq 0) { throw "Cannot determine the required directory path" }
$filepath = $filepath.TrimEnd("\")
return $filepath
}