internal/Get-XpDirTreeRestoreFile.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
function Get-XpDirTreeRestoreFile {
<#
    .SYNOPSIS
        Internal Function to get SQL Server backfiles from a specified folder using xp_dirtree
     
    .DESCRIPTION
        Takes path, checks for validity. Scans for usual backup file
     
    .PARAMETER Path
        The path to retrieve the restore for.
     
    .PARAMETER SqlInstance
        The SQL Server that you're connecting to.
     
    .PARAMETER SqlCredential
        Credential object used to connect to the SQL Server as a different user
     
    .PARAMETER Silent
        Setting this to true will disable all verbosity.
     
    .EXAMPLE
        PS C:\> Get-XpDirTreeRestoreFile -Path '\\foo\bar\' -SqlInstance $SqlInstance
     
        Tests whether the instance $SqlInstance has access to the path \\foo\bar\
#>

    [CmdletBinding()]
    Param (
        [parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [string]$Path,
        [parameter(Mandatory = $true)]
        [Alias("ServerInstance", "SqlServer")]
        [DbaInstanceParameter]$SqlInstance,
        [System.Management.Automation.PSCredential]$SqlCredential,
        [bool]$Silent = $false
    )
    
    Write-Message -Level InternalComment -Message "Starting"
    
    Write-Message -Level Verbose -Message "Connecting to $SqlInstance"
    $Server = Connect-SqlInstance -SqlInstance $SqlInstance -SqlCredential $SqlCredential
    
    if ($Path[-1] -ne "\") {
        $Path = $Path + "\"
    }
    
    If (!(Test-DbaSqlPath -SqlInstance $server -path $path)) {
        Stop-Function -Message "SqlInstance $SqlInstance cannot access $path" -Silent $true
    }
    
    $query = "EXEC master.sys.xp_dirtree '$Path',1,1;"
    $queryResult = Invoke-Sqlcmd2 -ServerInstance $SqlInstance -Credential $SqlCredential -Database tempdb -Query $query
    #$queryResult = $Server.Query($query)
    
    $dirs = $queryResult | where-object file -eq 0
    $Results = @()
    $Results += $queryResult | where-object file -eq 1 | Select-Object @{ Name = "FullName"; Expression = { $PATH + $_."Subdirectory" } }
    
    ForEach ($d in $dirs) {
        $fullpath = "$path$($d.Subdirectory)"
        Write-Message -Level Verbose -Message "Enumerating subdirectory '$fullpath'"
        $Results += Get-XpDirTreeRestoreFile -path $fullpath -SqlInstance $server
    }
    return $Results
    
}