Get DefaultFile and DefaultLog for a SMO server, in PowerShell

When working with SMO server object in PowerShell, some properties are not well populated, depending on the version, install location, or … who knows what other reasons.
The way to overpass that is to use some related properties, but be aware that they might not always meet your needs.

# Load assemblies
[Reflection.Assembly]::LoadWithPartialName(“Microsoft.SqlServer.SMO”) | Out-Null
[Reflection.Assembly]::LoadWithPartialName(“Microsoft.SqlServer.SmoExtended”) | Out-Null
[Reflection.Assembly]::LoadWithPartialName(“Microsoft.SqlServer.ConnectionInfo”) | Out-Null
[Reflection.Assembly]::LoadWithPartialName(“Microsoft.SqlServer.SmoEnum”) | Out-Null

# Create sql server object
$server = New-Object (“Microsoft.SqlServer.Management.Smo.Server”) “your server”

function Get-SqlServerDefaultFilePath($server) {
  # Determines the DefaultFile value for a SMO server,
  # given the fact that sometimes the value is not populated
  $defaultPath = ”
  if ($server) {
    $defaultPath = $server.DefaultFile
    if ($defaultPath.Length -eq 0) {
      $defaultPath = $server.Settings.DefaultFile
    }
    if ($defaultPath.Length -eq 0) {
      $defaultPath = $server.MasterDBPath
    }
    if ($defaultPath.Length -eq 0) {
      $defaultPath = $server.Information.MasterDBPath
    }
    if ($defaultPath.Length -eq 0) {
      $defaultPath = $server.InstallDataDirectory
    }
  }
  return $defaultPath
}

function Get-SqlServerDefaultLogPath($server) {
  # Determines the DefaultLog value for a SMO server,
  # given the fact that sometimes the value is not populated
  $defaultLog = ”
  if ($server) {
    $defaultLog = $server.DefaultLog
    if ($defaultLog.Length -eq 0) {
      $defaultLog = $server.Settings.DefaultLog
    }
    if ($defaultLog.Length -eq 0) {
      $defaultLog = $server.MasterDBLogPath
    }
    if ($defaultLog.Length -eq 0) {
      $defaultLog = $server.Information.MasterDBLogPath
    }
    if ($defaultLog.Length -eq 0) {
      $defaultLog = $server.InstallDataDirectory
    }
  }
  return $defaultLog
}

Note 1: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.
Note 2: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: