Get-FTPItem.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
Function Get-FTPItem
{
    <#
    .SYNOPSIS
        Send specific file from ftop server to location disk.
 
    .DESCRIPTION
        The Get-FTPItem cmdlet download file to specific location on local machine.
         
    .PARAMETER Path
        Specifies a path to ftp location.
 
    .PARAMETER LocalPath
        Specifies a local path.
         
    .PARAMETER RecreateFolders
        Recreate locally folders structure from ftp server.
 
    .PARAMETER BufferSize
        Specifies size of buffer. Default is 20KB.
         
    .PARAMETER Session
        Specifies a friendly name for the ftp session. Default session name is 'DefaultFTPSession'.
         
    .PARAMETER Overwrite
        Overwrite item in local path.
         
    .EXAMPLE
        PS P:\> Get-FTPItem -Path ftp://ftp.contoso.com/folder/subfolder1/test.xlsx -LocalPath P:\test
        226 File send OK.
 
        PS P:\> Get-FTPItem -Path ftp://ftp.contoso.com/folder/subfolder1/test.xlsx -LocalPath P:\test
 
        A File name already exists in location: P:\test
        What do you want to do?
        [C] Cancel [O] Overwrite [?] Help (default is "O"): O
        226 File send OK.
 
    .EXAMPLE
        PS P:\> Get-FTPChildItem -path folder/subfolder1 -Recurse | Get-FTPItem -localpath p:\test -RecreateFolders -Verbose
        VERBOSE: Performing operation "Download item: 'ftp://ftp.contoso.com/folder/subfolder1/test.xlsx'" on Target "p:\test\folder\subfolder1".
        VERBOSE: Creating folder: folder\subfolder1
        226 File send OK.
 
        VERBOSE: Performing operation "Download item: 'ftp://ftp.contoso.com/folder/subfolder1/ziped.zip'" on Target "p:\test\folder\subfolder1".
        226 File send OK.
 
        VERBOSE: Performing operation "Download item: 'ftp://ftp.contoso.com/folder/subfolder1/subfolder11/ziped.zip'" on Target "p:\test\folder\subfolder1\subfolder11".
        VERBOSE: Creating folder: folder\subfolder1\subfolder11
        226 File send OK.
 
    .NOTES
        Author: Michal Gajda
        Blog : http://commandlinegeeks.com/
 
    .LINK
        Get-FTPChildItem
    #>
    

    [CmdletBinding(
        SupportsShouldProcess=$True,
        ConfirmImpact="Low"
    )]
    Param(
        [parameter(Mandatory=$true,
            ValueFromPipelineByPropertyName=$true,
            ValueFromPipeline=$true)]
        [Alias("FullName")]
        [String]$Path = "",
        [String]$LocalPath = (Get-Location).Path,
        [Switch]$RecreateFolders,
        [Int]$BufferSize = 20KB,
        $Session = "DefaultFTPSession",
        [Switch]$Overwrite = $false
    )
    
    Begin
    {
        if($Session -isnot [String])
        {
            $CurrentSession = $Session
        }
        else
        {
            $CurrentSession = Get-Variable -Scope Global -Name $Session -ErrorAction SilentlyContinue -ValueOnly
        }
        
        if($CurrentSession -eq $null)
        {
            Write-Warning "Add-FTPItem: Cannot find session $Session. First use Set-FTPConnection to config FTP connection."
            Break
            Return
        }    
    }
    
    Process
    {
        Write-Debug "Native path: $Path"
        
        if($Path -match "ftp://")
        {
            $RequestUri = $Path
            Write-Debug "Use original path: $RequestUri"
            
        }
        else
        {
            $RequestUri = $CurrentSession.RequestUri.OriginalString+"/"+$Path
            Write-Debug "Add ftp:// at start: $RequestUri"
        }
        $RequestUri = [regex]::Replace($RequestUri, '/$', '')
        $RequestUri = [regex]::Replace($RequestUri, '/+', '/')
        $RequestUri = [regex]::Replace($RequestUri, '^ftp:/', 'ftp://')
        Write-Debug "Remove additonal slash: $RequestUri"
            
        if ($pscmdlet.ShouldProcess($LocalDir,"Download item: '$RequestUri'")) 
        {    
            $TotalData = Get-FTPItemSize $RequestUri -Session $Session -Silent
            if($TotalData -eq -1) { Return }
            if($TotalData -eq 0) { $TotalData = 1 }

            $AbsolutePath = ($RequestUri -split $CurrentSession.ServicePoint.Address.AbsoluteUri)[1]
            $LastIndex = $AbsolutePath.LastIndexOf("/")
            $ServerPath = $CurrentSession.ServicePoint.Address.AbsoluteUri
            if($LastIndex -eq -1)
            {
                $FolderPath = "\"
            }
            else
            {
                $FolderPath = $AbsolutePath.SubString(0,$LastIndex) -replace "/","\"
            }    
            $FileName = $AbsolutePath.SubString($LastIndex+1)
        
            if($RecreateFolders)
            {
                if(!(Test-Path (Join-Path -Path $LocalPath -ChildPath $FolderPath)))
                {
                    Write-Verbose "Creating folder: $FolderPath"
                    New-Item -Type Directory -Path $LocalPath -Name $FolderPath | Out-Null
                }
                $LocalDir = Join-Path -Path $LocalPath -ChildPath $FolderPath
            }
            else
            {
                $LocalDir = $LocalPath
            }            
            
            [System.Net.FtpWebRequest]$Request = [System.Net.WebRequest]::Create($RequestUri)
            $Request.Credentials = $CurrentSession.Credentials
            $Request.EnableSsl = $CurrentSession.EnableSsl
            $Request.KeepAlive = $CurrentSession.KeepAlive
            $Request.UseBinary = $CurrentSession.UseBinary
            $Request.UsePassive = $CurrentSession.UsePassive

            $Request.Method = [System.Net.WebRequestMethods+FTP]::DownloadFile  
            Write-Debug "Use WebRequestMethods: $($Request.Method)"
            Try
            {
                [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$CurrentSession.ignoreCert}
                $SendFlag = 1
                
                if((Get-ItemProperty $LocalDir -ErrorAction SilentlyContinue).Attributes -match "Directory")
                {
                    $LocalDir = Join-Path -Path $LocalDir -ChildPath $FileName
                }
                
                if(Test-Path ($LocalDir))
                {
                    $FileSize = (Get-Item $LocalDir).Length
                    
                    if($Overwrite -eq $false)
                    {
                        $Title = "A file ($RequestUri) already exists in location: $LocalDir"
                        $Message = "What do you want to do?"

                        $CDOverwrite = New-Object System.Management.Automation.Host.ChoiceDescription "&Overwrite"
                        $CDCancel = New-Object System.Management.Automation.Host.ChoiceDescription "&Cancel"
                        if($FileSize -lt $TotalData)
                        {
                            $CDResume = New-Object System.Management.Automation.Host.ChoiceDescription "&Resume"
                            $Options = [System.Management.Automation.Host.ChoiceDescription[]]($CDCancel, $CDOverwrite, $CDResume)
                            $SendFlag = $host.ui.PromptForChoice($Title, $Message, $Options, 2) 
                        }
                        else
                        {
                            $Options = [System.Management.Automation.Host.ChoiceDescription[]]($CDCancel, $CDOverwrite)
                            $SendFlag = $host.ui.PromptForChoice($Title, $Message, $Options, 1)
                        }
                    }
                    else
                    {
                        $SendFlag = 1
                    }
                }

                if($SendFlag)
                {
                    [Byte[]]$Buffer = New-Object Byte[] $BufferSize

                    $ReadedData = 0
                    $AllReadedData = 0
                    
                    if($SendFlag -eq 2)
                    {      
                        $File = New-Object IO.FileStream ($LocalDir,[IO.FileMode]::Append)
                        $Request.UseBinary = $True
                        $Request.ContentOffset  = $FileSize 
                        $AllReadedData = $FileSize
                        Write-Debug "Open File to append: $LocalDir"
                    }
                    else
                    {
                        $File = New-Object IO.FileStream ($LocalDir,[IO.FileMode]::Create)
                        Write-Debug "Create File: $LocalDir"
                    }
                    
                    $Response = $Request.GetResponse()
                    $Stream  = $Response.GetResponseStream()
                    
                    Do{
                        $ReadedData=$Stream.Read($Buffer,0,$Buffer.Length)
                        $AllReadedData +=$ReadedData
                        $File.Write($Buffer,0,$ReadedData)
                        if($TotalData)
                        {
                            Write-Progress -Activity "Download File: $Path" -Status "Downloading:" -Percentcomplete ([int]($AllReadedData/$TotalData * 100))
                        }
                    }
                    While ($ReadedData -ne 0)
                    $File.Close()
                    Write-Debug "Close File: $LocalDir"
                    
                    $Status = $Response.StatusDescription
                    $Response.Close()
                    Return $Status
                }
            }
            Catch
            {
                Write-Error $_.Exception.Message -ErrorAction Stop 
            }
        }
    }
    
    End{}
}