functions/Measure-DbaDiskSpaceRequirement.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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
function Measure-DbaDiskSpaceRequirement {
    <#
        .SYNOPSIS
            Calculate the space needed to copy and possibly replace a database from one SQL server to another.
 
        .DESCRIPTION
            Returns a file list from source and destination where source file may overwrite destination. Complex scenarios where a new file may exist is taken into account.
            This command will accept a hash object in pipeline with the following keys: Source, SourceDatabase, Destination. Using this command will provide a way to prepare before a complex migration with multiple databases from different sources and destinations.
 
        .PARAMETER Source
            Source SQL Server.
 
        .PARAMETER SourceSqlCredential
            Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)
 
        .PARAMETER Database
            The database to copy. It MUST exist.
 
        .PARAMETER Destination
            Destination SQL Server instance.
 
        .PARAMETER DestinationSqlCredential
            Login to the target instance using alternative credentials. Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)
 
        .PARAMETER DestinationDatabase
            The database name at destination.
            May or may not be present, if unspecified it will default to the database name provided in SourceDatabase.
 
        .PARAMETER Credential
            The credentials to use to connect via CIM/WMI/PowerShell remoting.
 
        .PARAMETER EnableException
            By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
            This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
            Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.
 
        .NOTES
            Tags: Database, DiskSpace, Migration
            Author: Pollus Brodeur (@pollusb)
 
            Website: https://dbatools.io
            Copyright: (C) Chrissy LeMaire, clemaire@gmail.com
            License: MIT https://opensource.org/licenses/MIT
 
        .LINK
            https://dbatools.io/Measure-DbaDiskSpaceRequirement
 
        .EXAMPLE
            Measure-DbaDiskSpaceRequirement -Source INSTANCE1 -Database DB1 -Destination INSTANCE2
 
            Calculate space needed for a simple migration with one database with the same name at destination.
 
        .EXAMPLE
            @([PSCustomObject]@{Source='SQL1';Destination='SQL2';Database='DB1'},
              [PSCustomObject]@{Source='SQL1';Destination='SQL2';Database='DB2'}
            ) | Measure-DbaDiskSpaceRequirement
 
            Using a PSCustomObject with 2 databases to migrate on SQL2.
 
        .EXAMPLE
            Import-Csv -Path .\migration.csv -Delimiter "`t" | Measure-DbaDiskSpaceRequirement | Format-Table -AutoSize
 
            Using a CSV file. You will need to use this header line "Source<tab>Destination<tab>Database<tab>DestinationDatabase".
 
        .EXAMPLE
            Invoke-DbaSqlCmd -SqlInstance DBA -Database Migrations -Query 'select Source, Destination, Database from dbo.Migrations' `
                | Measure-DbaDiskSpaceRequirement
 
            Using a SQL table. We are DBA after all!
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [DbaInstanceParameter]$Source,
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [string]$Database,
        [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)]
        [PSCredential]$SourceSqlCredential,
        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [DbaInstanceParameter]$Destination,
        [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)]
        [string]$DestinationDatabase,
        [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)]
        [PSCredential]$DestinationSqlCredential,
        [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)]
        [PSCredential]$Credential,
        [Alias('Silent')]
        [switch]$EnableException
    )
    begin {
        $local:cacheMP = @{}
        $local:cacheDP = @{}
        function Get-MountPoint {
            [CmdletBinding()]
            param(
                [Parameter(Mandatory = $true)]
                $computerName,
                [PSCredential]$credential
            )
            Get-DbaCmObject -Class Win32_MountPoint -ComputerName $computerName -Credential $credential |
                Select-Object @{n='Mountpoint';e={$_.Directory.split('=')[1].Replace('"','').Replace('\\','\')}}
        }
        function Get-MountPointFromPath {
            [CmdletBinding()]
            param(
                [Parameter(Mandatory = $true)]
                $path,
                [Parameter(Mandatory = $true)]
                $computerName,
                [PSCredential]$credential
            )
            if (!$cacheMP[$computerName]) {
                try {
                    $cacheMP.Add($computerName, (Get-MountPoint -computerName $computerName -credential $credential))
                    Write-Message -Level Verbose -Message "cacheMP[$computerName] is now cached"
                }
                catch {
                    # This way, I won't be asking again for this computer.
                    $cacheMP.Add($computerName, '?')
                    Stop-Function -Message "Can't connect to $computerName. cacheMP[$computerName] = ?" -ErrorRecord $_ -Target $computerName -Continue
                }
            }
            if ($cacheMP[$computerName] -eq '?') {
                return '?'
            }
            foreach ($m in ($cacheMP[$computerName] | Sort-Object -Property Mountpoint -Descending)) {
                if ($path -like "$($m.Mountpoint)*") {
                    return $m.Mountpoint
                }
            }
            Write-Message -Level Warning -Message "Path $path can't be found in any MountPoints of $computerName"
        }
        function Get-MountPointFromDefaultPath {
            [CmdletBinding()]
            param(
                [Parameter(Mandatory = $true)]
                [ValidateSet('Log', 'Data')]
                $DefaultPathType,
                [Parameter(Mandatory = $true)]
                $SqlInstance,
                [PSCredential]$SqlCredential,
                # Could probably use the computer defined in SqlInstance but info was already available from the caller
                $computerName,
                [PSCredential]$Credential
            )
            if (!$cacheDP[$SqlInstance]) {
                try {
                    $cacheDP.Add($SqlInstance, (Get-DbaDefaultPath -SqlInstance $SqlInstance -SqlCredential $SqlCredential -EnableException))
                    Write-Message -Level Verbose -Message "cacheDP[$SqlInstance] is now cached"
                }
                catch {
                    Stop-Function -Message "Can't connect to $SqlInstance" -Continue
                    $cacheDP.Add($SqlInstance, '?')
                    return '?'
                }
            }
            if ($cacheDP[$SqlInstance] -eq '?') {
                return '?'
            }
            if (!$computerName) {
                $computerName = $cacheDP[$SqlInstance].ComputerName
            }
            if (!$cacheMP[$computerName]) {
                try {
                    $cacheMP.Add($computerName, (Get-MountPoint -computerName $computerName -Credential $Credential))
                }
                catch {
                    Stop-Function -Message "Can't connect to $computerName." -Continue
                    $cacheMP.Add($computerName, '?')
                    return '?'
                }
            }
            if ($DefaultPathType -eq 'Log') {
                $path = $cacheDP[$SqlInstance].Log
            }
            else {
                $path = $cacheDP[$SqlInstance].Data
            }
            foreach ($m in ($cacheMP[$computerName] | Sort-Object -Property Mountpoint -Descending)) {
                if ($path -like "$($m.Mountpoint)*") {
                    return $m.Mountpoint
                }
            }
        }
    }
    process {
        Write-Message -Level Verbose -Message "Connecting to SQL Servers."
        try {
            Write-Message -Level Verbose -Message "Connecting to $Source."
            $sourceServer = Connect-SqlInstance -SqlInstance $Source -SqlCredential $SourceSqlCredential
        }
        catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Source
        }

        try {
            Write-Message -Level Verbose -Message "Connecting to $Destination."
            $destServer = Connect-SqlInstance -SqlInstance $Destination -SqlCredential $DestinationSqlCredential
        }
        catch {
            Stop-Function -Message "Failure" -Category ConnectionError -ErrorRecord $_ -Target $Destination
        }

        if (Test-Bound 'DestinationDatabase' -not) {
            $DestinationDatabase = $Database
        }
        Write-Message -Level Verbose -Message "$Source.[$Database] -> $Destination.[$DestinationDatabase]"

        $sourceDb = Get-DbaDatabase -SqlInstance $sourceServer -Database $Database -SqlCredential $SourceSqlCredential
        if (Test-Bound 'Database' -not) {
            Stop-Function -Message "Database [$Database] MUST exist on Source Instance $Source." -ErrorRecord $_
        }
        $sourceFiles = @($sourceDb.FileGroups.Files | Select-Object Name, FileName, Size, @{n='Type'; e= {'Data'}})
        $sourceFiles += @($sourceDb.LogFiles        | Select-Object Name, FileName, Size, @{n='Type'; e= {'Log'}})

        if ($destDb = Get-DbaDatabase -SqlInstance $destServer -Database $DestinationDatabase -SqlCredential $DestinationSqlCredential) {
            $destFiles = @($destDb.FileGroups.Files | Select-Object Name, FileName, Size, @{n='Type'; e= {'Data'}})
            $destFiles += @($destDb.LogFiles        | Select-Object Name, FileName, Size, @{n='Type'; e= {'Log'}})
            $computerName = $destDb.ComputerName
        }
        else {
            Write-Message -Level Verbose -Message "Database [$DestinationDatabase] does not exist on Destination Instance $Destination."
            $computerName = $destServer.ComputerName
        }

        foreach ($sourceFile in $sourceFiles) {
            foreach ($destFile in $destFiles) {
                if ($found = ($sourceFile.Name -eq $destFile.Name)) {
                    # Files found on both sides
                    [PSCustomObject]@{
                            SourceComputerName      = $sourceServer.ComputerName
                            SourceInstance          = $sourceServer.ServiceName
                            SourceSqlInstance       = $sourceServer.DomainInstanceName
                            DestinationComputerName = $destServer.ComputerName
                            DestinationInstance     = $destServer.ServiceName
                            DestinationSqlInstance  = $destServer.DomainInstanceName
                            SourceDatabase          = $sourceDb.Name
                            SourceLogicalName       = $sourceFile.Name
                            SourceFileName          = $sourceFile.FileName
                            SourceFileSize          = [DbaSize]($sourceFile.Size * 1000)
                            DestinationDatabase     = $destDb.Name
                            DestinationLogicalName  = $destFile.Name
                            DestinationFileName     = $destFile.FileName
                            DestinationFileSize     = [DbaSize]($destFile.Size * 1000) * -1
                            DifferenceSize          = [DbaSize]( ($sourceFile.Size * 1000) - ($destFile.Size * 1000) )
                            MountPoint              = Get-MountPointFromPath -Path $destFile.Filename -ComputerName $computerName -Credential $Credential
                            FileLocation            = 'Source and Destination'
                        } | Select-DefaultView -ExcludeProperty SourceComputerName, SourceInstance, DestinationInstance, DestinationLogicalName
                    break
                }
            }
            if (!$found) {
                # Files on source but not on destination
                [PSCustomObject]@{
                        SourceComputerName      = $sourceServer.ComputerName
                        SourceInstance          = $sourceServer.ServiceName
                        SourceSqlInstance       = $sourceServer.DomainInstanceName
                        DestinationComputerName = $destServer.ComputerName
                        DestinationInstance     = $destServer.ServiceName
                        DestinationSqlInstance  = $destServer.DomainInstanceName
                        SourceDatabase          = $sourceDb.Name
                        SourceLogicalName       = $sourceFile.Name
                        SourceFileName          = $sourceFile.FileName
                        SourceFileSize          = [DbaSize]($sourceFile.Size * 1000)
                        DestinationDatabase     = $DestinationDatabase
                        DestinationLogicalName  = $null
                        DestinationFileName     = $null
                        DestinationFileSize     = [DbaSize]0
                        DifferenceSize          = [DbaSize]($sourceFile.Size * 1000)
                        MountPoint              = Get-MountPointFromDefaultPath -DefaultPathType $sourceFile.Type -SqlInstance $Destination `
                                                  -SqlCredential $DestinationSqlCredential -computerName $computerName -credential $Credential
                        FileLocation            = 'Only on Source'
                    } | Select-DefaultView -ExcludeProperty SourceComputerName, SourceInstance, DestinationInstance, DestinationLogicalName
            }
        }
        if ($destDb) {
            # Files on destination but not on source (strange scenario but possible)
            $destFilesNotSource = Compare-Object -ReferenceObject $destFiles -DifferenceObject $sourceFiles -Property Name -PassThru
            foreach ($destFileNotSource in $destFilesNotSource) {
                [PSCustomObject]@{
                        SourceComputerName      = $sourceServer.ComputerName
                        SourceInstance          = $sourceServer.ServiceName
                        SourceSqlInstance       = $sourceServer.DomainInstanceName
                        DestinationComputerName = $destServer.ComputerName
                        DestinationInstance     = $destServer.ServiceName
                        DestinationSqlInstance  = $destServer.DomainInstanceName
                        SourceDatabaseName      = $Database
                        SourceLogicalName       = $null
                        SourceFileName          = $null
                        SourceFileSize          = [DbaSize]0
                        DestinationDatabaseName = $destDb.Name
                        DestinationLogicalName  = $destFileNotSource.Name
                        DestinationFileName     = $destFile.FileName
                        DestinationFileSize     = [DbaSize]($destFileNotSource.Size * 1000) * -1
                        DifferenceSize          = [DbaSize]($destFileNotSource.Size * 1000) * -1
                        MountPoint              = Get-MountPointFromPath -Path $destFileNotSource.Filename -ComputerName $computerName -Credential $Credential
                        FileLocation            = 'Only on Destination'
                    } | Select-DefaultView -ExcludeProperty SourceComputerName, SourceInstance, DestinationInstance, DestinationLogicalName
            }
        }
        $DestinationDatabase = $null
    }
}