Get-FTPChildItem.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
Function Get-FTPChildItem
{
    <#
    .SYNOPSIS
        Gets the item and child items from ftp location.
 
    .DESCRIPTION
        The Get-FTPChildItem cmdlet gets the items from ftp locations. If the item is a container, it gets the items inside the container, known as child items.
         
    .PARAMETER Path
        Specifies a path to ftp location or file.
             
    .PARAMETER Session
        Specifies a friendly name for the ftp session. Default session name is 'DefaultFTPSession'.
         
    .PARAMETER Recurse
        Get recurse child items.
 
    .PARAMETER Depth
        Define depth of folder in recurse mode. Autoenable recurse mode.
 
    .PARAMETER Filter
        Specifies a filter parameter to return only this objects that have proper name. This parameter allow to use of wildcards. Defalut value is *.
         
    .EXAMPLE
        PS P:\> Get-FTPChildItem -path ftp://ftp.contoso.com/folder
 
 
           Parent: ftp://ftp.contoso.com/folder
 
        Dir Right Ln User Group Size ModifiedDate Name
        --- ----- -- ---- ----- ---- ------------ ----
        d rwxr-xr-x 3 ftp ftp 2012-06-19 12:58:00 subfolder1
        d rwxr-xr-x 2 ftp ftp 2012-06-19 12:58:00 subfolder2
        - rw-r--r-- 1 ftp ftp 1KB 2012-06-15 12:49:00 textitem.txt
 
    .EXAMPLE
        PS P:\> Get-FTPChildItem -path ftp://ftp.contoso.com/folder -Filter "subfolder*"
 
 
           Parent: ftp://ftp.contoso.com/folder
 
        Dir Right Ln User Group Size ModifiedDate Name
        --- ----- -- ---- ----- ---- ------------ ----
        d rwxr-xr-x 3 ftp ftp 2012-06-19 12:58:00 subfolder1
        d rwxr-xr-x 2 ftp ftp 2012-06-19 12:58:00 subfolder2
 
    .EXAMPLE
        PS P:\> Get-FTPChildItem -path folder -Recurse
 
 
           Parent: ftp://ftp.contoso.com/folder
 
        Dir Right Ln User Group Size ModifiedDate Name
        --- ----- -- ---- ----- ---- ------------ ----
        d rwxr-xr-x 3 ftp ftp 2012-06-19 12:58:00 subfolder1
        d rwxr-xr-x 2 ftp ftp 2012-06-19 12:58:00 subfolder2
        - rw-r--r-- 1 ftp ftp 1KB 2012-06-15 12:49:00 textitem.txt
 
 
           Parent: ftp://ftp.contoso.com/folder/subfolder1
 
        Dir Right Ln User Group Size ModifiedDate Name
        --- ----- -- ---- ----- ---- ------------ ----
        d rwxr-xr-x 2 ftp ftp 2012-06-19 12:58:00 subfolder11
        - rw-r--r-- 1 ftp ftp 21KB 2012-06-19 09:20:00 test.xlsx
        - rw-r--r-- 1 ftp ftp 14KB 2012-06-19 11:27:00 ziped.zip
 
 
           Parent: ftp://ftp.contoso.com/folder/subfolder1/subfolder11
 
        Dir Right Ln User Group Size ModifiedDate Name
        --- ----- -- ---- ----- ---- ------------ ----
        - rw-r--r-- 1 ftp ftp 14KB 2012-06-19 11:27:00 ziped.zip
 
 
           Parent: ftp://ftp.contoso.com/folder/subfolder2
 
        Dir Right Ln User Group Size ModifiedDate Name
        --- ----- -- ---- ----- ---- ------------ ----
        - rw-r--r-- 1 ftp ftp 1KB 2012-06-15 12:49:00 textitem.txt
        - rw-r--r-- 1 ftp ftp 14KB 2012-06-19 11:27:00 ziped.zip
 
    .EXAMPLE
        PS P:\> $ftpFile = Get-FTPChildItem -path /folder/subfolder1/test.xlsx
        PS P:\> $ftpFile | Select-Object Parent, Name, ModifiedDate
 
        Parent Name ModifiedDate
        ------ ---- ------------
        ftp://ftp.contoso.com/folder/subfolder1 test.xlsx 2012-06-19 09:20:00
         
    .NOTES
        Author: Michal Gajda
        Blog : http://commandlinegeeks.com/
 
    .LINK
        Set-FTPConnection
    #>
     

    [OutputType('PSFTP.Item')]
    [CmdletBinding(
        SupportsShouldProcess=$True,
        ConfirmImpact="Low"
    )]
    Param(
        [parameter(ValueFromPipelineByPropertyName=$true,
            ValueFromPipeline=$true)]
        [String]$Path = "",
        $Session = "DefaultFTPSession",
        [parameter(ValueFromPipelineByPropertyName=$true)]
        [Switch]$Recurse,    
        [Int]$Depth = 0,        
        [String]$Filter = "*"
    )
    
    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-Verbose "Use original path: $RequestUri"
            
        }
        else
        {
            $RequestUri = $CurrentSession.RequestUri.OriginalString+"/"+$Path
            Write-Verbose "Add ftp:// at start: $RequestUri"
        }
        $RequestUri = [regex]::Replace($RequestUri, '/$', '')
        $RequestUri = [regex]::Replace($RequestUri, '/+', '/')
        $RequestUri = [regex]::Replace($RequestUri, '^ftp:/', 'ftp://')
        Write-Verbose "Remove additonal slash: $RequestUri"

        if($Depth -gt 0)
        {
            $CurrentDepth = [regex]::matches($RequestUri,"/").count
            if((Get-Variable -Scope Script -Name MaxDepth -ErrorAction SilentlyContinue) -eq $null)
            {
                New-Variable -Scope Script -Name MaxDepth -Value ([Int]$CurrentDepth +$Depth)
            }
        
            Write-Verbose "Auto enable recurse mode. Current depth / Max Depth: $CurrentDepth / $($Script:MaxDepth)"
            $Recurse = $true
        }

        
        if ($pscmdlet.ShouldProcess($RequestUri,"Get child items from ftp location")) 
        {    
            if((Get-FTPItemSize $RequestUri -Session $Session -Silent) -eq -1)
            {
                Write-Verbose "Path is directory"
                $ParentPath = $RequestUri
            }
            else
            {
                Write-Verbose "Path is file. Delete last file name to get parent path."
                $LastIndex = $RequestUri.LastIndexOf("/")
                $ParentPath = $RequestUri.SubString(0,$LastIndex)
            }
                        
            [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]::ListDirectoryDetails
            Write-Verbose "Use WebRequestMethods: $($Request.Method)"
            Try
            {
                $mode = "Unknown"
                [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$CurrentSession.ignoreCert}
                $Response = $Request.GetResponse()
                
                [System.IO.StreamReader]$Stream = New-Object System.IO.StreamReader($Response.GetResponseStream(),[System.Text.Encoding]::Default)

                $DirList = @()
                $ItemsCollection = @()
                Try
                {
                    [string]$Line = $Stream.ReadLine()
                    Write-Debug "Read Line: $Line"
                }
                Catch
                {
                    $Line = $null
                    Write-Debug "Line is null"
                }
                
                While ($Line)
                {
                    if($mode -eq "Compatible" -or $mode -eq "Unknown")
                    {
                        $null, [string]$IsDirectory, [string]$Flag, [string]$Link, [string]$UserName, [string]$GroupName, [string]$Size, [string]$Date, [string]$Name = `
                        [regex]::split($Line,'^([d-])([rwxt-]{9})\s+(\d{1,})\s+([.@A-Za-z0-9-]+)\s+([A-Za-z0-9-]+)\s+(\d{1,})\s+(\w+\s+\d{1,2}\s+\d{1,2}:?\d{2})\s+(.+?)\s?$',"SingleLine,IgnoreCase,IgnorePatternWhitespace")

                        if($IsDirectory -eq "" -and $mode -eq "Unknown")
                        {
                            $mode = "IIS6"
                        }
                        elseif($mode -ne "Compatible")
                        {
                            $mode = "Compatible" #IIS7/Linux
                        }
                        
                        if($mode -eq "Compatible")
                        {
                            $DatePart = $Date -split "\s+"
                            $NewDateString = "$($DatePart[0]) $('{0:D2}' -f [int]$DatePart[1]) $($DatePart[2])"
                            
                            Try
                            {
                                if($DatePart[2] -match ":")
                                {
                                    $Month = ([DateTime]::ParseExact($DatePart[0],"MMM",[System.Globalization.CultureInfo]::InvariantCulture)).Month
                                    if((Get-Date).Month -ge $Month)
                                    {
                                        $NewDate = [DateTime]::ParseExact($NewDateString,"MMM dd HH:mm",[System.Globalization.CultureInfo]::InvariantCulture)
                                    }
                                    else
                                    {
                                        $NewDate = ([DateTime]::ParseExact($NewDateString,"MMM dd HH:mm",[System.Globalization.CultureInfo]::InvariantCulture)).AddYears(-1)
                                    }
                                }
                                else
                                {
                                    $NewDate = [DateTime]::ParseExact($NewDateString,"MMM dd yyyy",[System.Globalization.CultureInfo]::InvariantCulture)
                                }
                            }
                            Catch
                            {
                                Write-Verbose "Can't parse date: $Date"
                            }                            
                        }
                    }
                    
                    if($mode -eq "IIS6")
                    {
                        $null, [string]$NewDate, [string]$IsDirectory, [string]$Size, [string]$Name = `
                        [regex]::split($Line,'^(\d{2}-\d{2}-\d{2}\s+\d{2}:\d{2}[AP]M)\s+<*([DIR]*)>*\s+(\d*)\s+(.+).*$',"SingleLine,IgnoreCase")
                        
                        if($IsDirectory -eq "")
                        {
                            $IsDirectory = "-"
                        }
                    }
                    
                    Switch($Size)
                    {
                        {[int64]$_ -lt 1024} { $HFSize = $_+"B"; break }
                        {[System.Math]::Round([int64]$_/1KB,0) -lt 1024} { $HFSize = [String]([System.Math]::Round($_/1KB,0))+"KB"; break }
                        {[System.Math]::Round([int64]$_/1MB,0) -lt 1024} { $HFSize = [String]([System.Math]::Round($_/1MB,0))+"MB"; break }
                        {[System.Math]::Round([int64]$_/1GB,0) -lt 1024} { $HFSize = [String]([System.Math]::Round($_/1GB,0))+"GB"; break }
                        {[System.Math]::Round([int64]$_/1TB,0) -lt 1024} { $HFSize = [String]([System.Math]::Round($_/1TB,0))+"TB"; break }
                        {[System.Math]::Round([int64]$_/1PB,0) -lt 1024} { $HFSize = [String]([System.Math]::Round($_/1PB,0))+"PB"; break }
                    } 
                    
                    if($IsDirectory -eq "d" -or $IsDirectory -eq "DIR")
                    {
                        $HFSize = ""
                    }
                    
                    if($ParentPath -match "\*|\?")
                    {
                        $LastIndex = $ParentPath.LastIndexOf("/")
                        $ParentPath = $ParentPath.SubString(0,$LastIndex)
                        $ParentPath.Trim() + "/" + $Name.Trim()
                    }
                    
                    $LineObj = New-Object PSObject -Property @{
                        Dir = $IsDirectory
                        Right = $Flag
                        Ln = $Link
                        User = $UserName
                        Group = $GroupName
                        Size = $HFSize
                        SizeInByte = $Size
                        OrgModifiedDate = $Date
                        ModifiedDate = $NewDate
                        Name = $Name.Trim()
                        FullName = $ParentPath.Trim() + "/" + $Name.Trim()
                        Parent = $ParentPath.Trim()
                    }
                    
                    $LineObj.PSTypeNames.Clear()
                    $LineObj.PSTypeNames.Add('PSFTP.Item')
            
                    if($Recurse -and ($LineObj.Dir -eq "d" -or $LineObj.Dir -eq "DIR"))
                    {
                        $DirList += $LineObj
                    }
                    
                    
                    if($LineObj.Dir)
                    {
                        if($LineObj.Name -like $Filter)
                        {
                            Write-Debug "Filter accepted: $Filter"
                            $ItemsCollection += $LineObj
                        }
                    }
                    $Line = $Stream.ReadLine()
                    Write-Debug "Read Line: $Line"
                }
                
                $Response.Close()
                
                if($Recurse -and ($CurrentDepth -lt $Script:MaxDepth -or $Depth -eq 0))
                {
                    $RecurseResult = @()
                    $DirList | ForEach-Object {
                        Write-Debug "Recurse is active and go to: $($_.FullName)"
                        $RecurseResult += Get-FTPChildItem -Path ($_.FullName) -Session $Session -Recurse -Filter $Filter -Depth $Depth
                        
                    }    

                    $ItemsCollection += $RecurseResult
                }    
                
                if($ItemsCollection.count -eq 0)
                {
                    Return 
                }
                else
                {
                    Return $ItemsCollection | Sort-Object -Property @{Expression="Parent";Descending=$false}, @{Expression="Dir";Descending=$true}, @{Expression="Name";Descending=$false} 
                }
            }
            Catch
            {
                Write-Error $_.Exception.Message -ErrorAction Stop 
            }
        }
        
        if($CurrentDepth -ge $Script:MaxDepth)
        {
            Remove-Variable -Scope Script -Name CurrentDepth 
        }        
    }
    
    End{}
}