-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathGetDirectories
72 lines (66 loc) · 1.4 KB
/
GetDirectories
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
function Get-Directories
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true,
ValueFromPipeline = $true,
Position = 0)]
[System.IO.FileInfo]$Path,
[Parameter(Position = 1)]
[String]$SearchPattern = '*.*'
)
Begin
{
# an arraylist to hold the results
$result = New-Object -TypeName System.Collections.ArrayList
# a stack object to push directories that needs to be processed
$pending = New-Object System.Collections.Generic.Stack[String]
}
Process
{
# push all provided paths to the stack
foreach ($entry in $Path)
{
$pending.Push($entry)
}
# loop through the stack
while ($pending.Count -ne 0)
{
# current item to process
$current = $pending.Pop()
try
{
# get all subdirectories from the current one
# handle in try..catch e.g. to catch Access Denied
$next = [IO.Directory]::GetDirectories($current, $SearchPattern)
if ($null -ne $next)
{
ForEach ($dir in $next)
{
# add directory to the result list
[void]$result.Add($dir)
}
}
}
# ignore exceptions
catch { }
try
{
# we need to call GetDirectories for all directories that we found
$next = [IO.Directory]::GetDirectories($current, $SearchPattern)
ForEach ($dir in $next)
{
# push subdir to stack
$pending.Push($dir)
}
}
# ignore exceptions
catch { }
}
}
End
{
return $result
}
}