Add-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
248
249
250
251
252
253
254
255
Function Add-FTPItem
{
    <#
    .SYNOPSIS
        Send file to specific ftp location.
 
    .DESCRIPTION
        The Add-FTPItem cmdlet send file to specific location on ftp server.
         
    .PARAMETER Path
        Specifies a path to ftp location.
 
    .PARAMETER LocalPath
        Specifies a local path.
 
    .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 on remote location.
     
    .EXAMPLE
        PS> Add-FTPItem -Path "/myfolder" -LocalPath "C:\myFile.txt"
 
        Dir : -
        Right : rw-r--r--
        Ln : 1
        User : ftp
        Group : ftp
        Size : 82033
        ModifiedDate : Aug 17 12:27
        Name : myFile.txt
         
    .EXAMPLE
        PS> Get-ChildItem "C:\Folder" | Add-FTPItem
 
    .NOTES
        Author: Michal Gajda
        Blog : http://commandlinegeeks.com/
 
    .LINK
        Get-FTPChildItem
    #>
    

    [CmdletBinding(
        SupportsShouldProcess=$True,
        ConfirmImpact="Low"
    )]
    Param(
        [String]$Path = "",
        [parameter(Mandatory=$true,
            ValueFromPipelineByPropertyName=$true,
            ValueFromPipeline=$true)]
        [Alias("FullName")]        
        [String]$LocalPath,
        [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
    {
        if(Test-Path $LocalPath)
        {
            $LocalItem = Get-Item $LocalPath
            $ItemName = ($LocalItem).Name

            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"
            }

            if($LocalItem -is [System.IO.DirectoryInfo])
            {
                if($CurrentSession.StartPath -eq "")
                {
                    $CurrentSession.StartPath =  $LocalItem.Parent.FullName -replace "\\","\\"
                }

                $CurrentSession = Get-Variable -Scope Global -Name $Session -ErrorAction SilentlyContinue -ValueOnly
                $StartLocalPath =  $CurrentSession.StartPath
                $PartLocalPath = $LocalPath -replace $StartLocalPath
                $RemotePath = $PartLocalPath -replace "\\","/"
                $RequestUri = $RequestUri+"/"+$RemotePath
                $RequestUri = $RequestUri -replace $ItemName
                $RequestUri = [regex]::Replace($RequestUri, '/$', '')
                $RequestUri = [regex]::Replace($RequestUri, '/+', '/')
                $RequestUri = [regex]::Replace($RequestUri, '^ftp:/', 'ftp://')

                Try
                {
                    New-FTPItem -Path $RequestUri -Name $ItemName
                }
                Catch
                {
                    Write-Debug "Probably folder $ItemName exist in path $RequestUri"
                }
            }
            else
            {
                <#$RequestUri = $RequestUri+"/"+$ItemName
                $RequestUri = [regex]::Replace($RequestUri, '/$', '')
                $RequestUri = [regex]::Replace($RequestUri, '/+', '/')
                $RequestUri = [regex]::Replace($RequestUri, '^ftp:/', 'ftp://')#>

                $CurrentSession = Get-Variable -Scope Global -Name $Session -ErrorAction SilentlyContinue -ValueOnly
                $StartLocalPath =  $CurrentSession.StartPath
                $PartLocalPath = $LocalPath -replace $StartLocalPath
                $RemotePath = $PartLocalPath -replace "\\","/"
                $RequestUri = $RequestUri+"/"+$RemotePath
                $RequestUri = [regex]::Replace($RequestUri, '/$', '')
                $RequestUri = [regex]::Replace($RequestUri, '/+', '/')
                $RequestUri = [regex]::Replace($RequestUri, '^ftp:/', 'ftp://')

                Write-Debug "Remove additonal slash: $RequestUri"
                
                if ($pscmdlet.ShouldProcess($RequestUri,"Send item: '$LocalPath' in ftp location")) 
                {    
                    [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

                    Try
                    {

                        [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$CurrentSession.ignoreCert}
                    
                        $SendFlag = 1

                        if($Overwrite -eq $false)
                        {
                            $FileSize = Get-FTPItemSize -Path $RequestUri -Session $Session -Silent
                            if($FileSize -gt 0)
                            {
                                $FileSize = Get-FTPItemSize -Path $RequestUri -Session $Session -Silent
                            
                                $Title = "A File name: $ItemName already exists in this location."
                                $Message = "What do you want to do?"

                                $ChoiceOverwrite = New-Object System.Management.Automation.Host.ChoiceDescription "&Overwrite"
                                $ChoiceCancel = New-Object System.Management.Automation.Host.ChoiceDescription "&Cancel"
                                if($FileSize -lt (Get-Item -Path $LocalPath).Length)
                                {
                                    $ChoiceResume = New-Object System.Management.Automation.Host.ChoiceDescription "&Resume"
                                    $Options = [System.Management.Automation.Host.ChoiceDescription[]]($ChoiceCancel, $ChoiceOverwrite, $ChoiceResume)
                                    $SendFlag = $host.ui.PromptForChoice($Title, $Message, $Options, 2) 
                                }
                                else
                                {
                                    $Options = [System.Management.Automation.Host.ChoiceDescription[]]($ChoiceCancel, $ChoiceOverwrite)
                                    $SendFlag = $host.ui.PromptForChoice($Title, $Message, $Options, 1) 
                                }    
                            }
                        }
            
                        if($SendFlag -eq 2)
                        {
                            $Request.Method = [System.Net.WebRequestMethods+FTP]::AppendFile
                        }
                        else
                        {
                            $Request.Method = [System.Net.WebRequestMethods+FTP]::UploadFile
                        }
                        Write-Debug "Use WebRequestMethods: $($Request.Method)"
                    
                        if($SendFlag)
                        {
                            $File = [IO.File]::OpenRead( (Convert-Path $LocalPath) )
                            Write-Debug "Open File: $LocalPath"
                        
                               $Response = $Request.GetRequestStream()
                            [Byte[]]$Buffer = New-Object Byte[] $BufferSize
                        
                            $ReadedData = 0
                            $AllReadedData = 0
                            $TotalData = (Get-Item $LocalPath).Length
                        
                            if($SendFlag -eq 2)
                            {
                                $SeekOrigin = [System.IO.SeekOrigin]::Begin
                                $File.Seek($FileSize,$SeekOrigin) | Out-Null
                                $AllReadedData = $FileSize
                            }
                        
                            if($TotalData -eq 0)
                            {
                                $TotalData = 1
                            }
                        
                            Do {
                                   $ReadedData = $File.Read($Buffer, 0, $Buffer.Length)
                                   $AllReadedData += $ReadedData
                                   $Response.Write($Buffer, 0, $ReadedData);
                                   Write-Progress -Activity "Upload File: $Path/$ItemName" -Status "Uploading:" -Percentcomplete ([int]($AllReadedData/$TotalData * 100))
                            } While($ReadedData -gt 0)
            
                            $File.Close()
                            $Response.Close()
                            Write-Debug "Close File: $LocalPath"
                        
                            Return Get-FTPChildItem -Path $RequestUri -Session $Session
                        }
                    
                    }
                    Catch
                    {
                        Write-Error $_.Exception.Message -ErrorAction Stop 
                    }
                }
            }
        }
        else
        {
            Write-Error "Cannot find local path '$LocalPath' because it does not exist." -ErrorAction Stop 
        }
    }
    
    End
    {
        $CurrentSession.StartPath = ""
    }                
}