functions/Mount-DbaDatabase.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
function Mount-DbaDatabase {
    <#
  .SYNOPSIS
   Attach a SQL Server Database - aliased to Attach-DbaDatabase
 
  .DESCRIPTION
   This command will attach a SQL Server database
 
  .PARAMETER SqlInstance
   The target SQL Server
 
  .PARAMETER SqlCredential
   PSCredential object to connect as. If not specified, current Windows login will be used
 
  .PARAMETER Database
   A string value that specifies the name of the database or databases to be attached
 
  .PARAMETER FileStructure
   A StringCollection object value that contains a list database files. If FileStructure is not specified, BackupHistory will be used to guess the structure.
  
  .PARAMETER DatabaseOwner
   Sets the database owner for the database. The sa account (or equialent) will be used if DatabaseOwner is not specified.
 
  .PARAMETER AttachOption
   A AttachOptions object value that contains the attachment options. Valid options include
   None, RebuildLog, EnableBroker, NewBroker and ErrorBrokerConversations
  
  .PARAMETER WhatIf
   Shows what would happen if the command were to run. No actions are actually performed
 
  .PARAMETER Confirm
   Prompts you for confirmation before executing any changing operations within the command
 
  .PARAMETER Silent
   Use this switch to disable any kind of verbose messages
 
  .NOTES
   Tags: Database
   Website: https://dbatools.io
   Copyright: (C) Chrissy LeMaire, clemaire@gmail.com
   License: GNU GPL v3 https://opensource.org/licenses/GPL-3.0
 
  .LINK
   https://dbatools.io/Mount-DbaDatabase
 
  .EXAMPLE
   $fileStructure = New-Object System.Collections.Specialized.StringCollection
   $fileStructure.Add("E:\archive\example.mdf")
   $filestructure.Add("E:\archive\example.ldf")
   $filestructure.Add("E:\archive\example.ndf")
   Mount-DbaDatabase -SqlInstance sql2016 -Database example -FileStructure $fileStructure
  
   Will mount a database named "example" to sql2016 with the files "E:\archive\example.mdf", "E:\archive\example.ldf", "E:\archive\example.ndf".
   The database will be given the owner "sa" and the attach option is None (as opposed to rebuildlog, enable broker, new broker, or errorbrokerconversations
  
  .EXAMPLE
   Mount-DbaDatabase -SqlInstance sql2016 -Database example
  
   Since the FileStructure was not provided, this command will attempt to determine it based on backup history. If found, a database named example will be attached to sql2016.
  
  .EXAMPLE
   Mount-DbaDatabase -SqlInstance sql2016 -Database example -WhatIf
    
   Shows what would happen if the command were executed (without actually performing the command)
 #>

    [CmdletBinding(SupportsShouldProcess)]
    Param (
        [parameter(Mandatory, ValueFromPipeline)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter[]]$SqlInstance,
        [PSCredential]
        $SqlCredential,
        [parameter(Mandatory)]
        [string[]]$Database,
        [System.Collections.Specialized.StringCollection]$FileStructure,
        [string]$DatabaseOwner,
        [ValidateSet('None','RebuildLog','EnableBroker','NewBroker', 'ErrorBrokerConversations')]
        [string]$AttachOption = "None",
        [switch]$Silent
    )
    process {        
        foreach ($instance in $SqlInstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $sqlcredential
            }
            catch {
                Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }
            
            if (-not $server.Logins.Item($DatabaseOwner)) {
                try {
                    $DatabaseOwner = ($server.Logins | Where-Object { $_.id -eq 1 }).Name
                }
                catch {
                    $DatabaseOwner = "sa"
                }
            }
            
            foreach ($db in $database) {
                
                if ($server.Databases[$db]) {
                    Stop-Function -Message "$db is already attached to $server" -Target $db -Continue
                }
                
                if ($server.Databases[$db].IsSystemObject) {
                    Stop-Function -Message "$db is a system database and cannot be attached using this method" -Target $db -Continue
                }
                
                if (-Not (Test-Bound -Parameter FileStructure)) {
                    #$backuphistory = Get-DbaBackupHistory -SqlInstance $server -LastFull -Database $db
                    $backuphistory = Get-DbaBackupHistory -SqlInstance $server -Database $db -Type Full | Sort-Object End -Descending | Select-Object -First 1

                    if (-not $backuphistory) {
                        $message = "Could not enumerate backup history to automatically build FileStructure. Rerun the command and provide the filestructure parameter"
                        Stop-Function -Message $message -Target $db -Continue
                    }
                    
                    $backupfile = $backuphistory.Path[0]
                    $filepaths = (Read-DbaBackupHeader -SqlInstance $server -FileList -Path $backupfile).PhysicalName
                    
                    $FileStructure = New-Object System.Collections.Specialized.StringCollection
                    foreach ($file in $filepaths) {
                        $exists = Test-DbaSqlpath -SqlInstance $server -Path $file
                        if (-not $exists) {
                            $message = "Could not find the files to build the FileStructure. Rerun the command and provide the FileStructure parameter"
                            Stop-Function -Message $message -Target $file -Continue
                        }
                        
                        $null = $FileStructure.Add($file)
                    }
                }
                
                If ($Pscmdlet.ShouldProcess($server, "Attaching $Database with $DatabaseOwner as database owner and $AttachOption as attachoption")) {
                    try {
                        $server.AttachDatabase($db, $FileStructure, $DatabaseOwner, [Microsoft.SqlServer.Management.Smo.AttachOptions]::$AttachOption)
                        
                        [pscustomobject]@{
                            ComputerName = $server.NetName
                            InstanceName = $server.ServiceName
                            SqlInstance = $server.DomainInstanceName
                            Database = $db
                            AttachResult = "Success"
                            AttachOption = $AttachOption
                            FileStructure = $FileStructure
                        }
                    }
                    catch {
                        Stop-Function -Message "Failure" -ErrorRecord $_ -Target $server
                    }
                }
            }
        }
    }
}