PSFolderSize.psm1

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
function Get-FolderSize {
    <#
    .SYNOPSIS

    Get-FolderSize
    Returns the size of folders in MB and GB.
    You can change the base path, omit folders, as well as output results in various formats.

    .DESCRIPTION

    This function will get the folder size in MB and GB of folders found in the basePath parameter.
    The basePath parameter defaults to C:\Users. You can also specify a specific folder name via the folderName parameter.

    VERSION HISTORY:
    1.0 - Updated object creation, removed try/catch that was causing issues
    0.5 - Just created!


    .PARAMETER BasePath

    This parameter allows you to specify the base path you'd like to get the child folders of.
    It defaults to where the module was run from via (Get-Location).

    .PARAMETER FolderName

    This parameter allows you to specify the name of a specific folder you'd like to get the size of.

    .PARAMETER AddTotal

    This parameter adds a total count at the end of the array

    .PARAMETER OmitFolders

    This parameter allows you to omit folder(s) (array of string) from being included

    .PARAMETER Output

    Use this option to output the results. Valid options are csv, xml, or json.

    .PARAMETER OutputPath

    Specify the path you want to use when outputting the results as a csv, xml, or json file.

    Do not include a trailing slash.

    Example: C:\users\you\Desktop

    Defaults to (Get-Location)
    This will be where you called the module from.

    .PARAMETER OutputFile

    This allows you to specify the path and file name you'd like for output.
    
    Example: C:\users\you\desktop\output.csv

    .EXAMPLE

    Get-FolderSize | Format-Table -AutoSize
    -------------------------------------

    FolderName Size(Bytes) Size(MB) Size(GB)
    ---------- ----------- -------- --------
    $GetCurrent 193768 0.18 MB 0.00 GB
    $RECYCLE.BIN 20649823 19.69 MB 0.02 GB
    $SysReset 53267392 50.80 MB 0.05 GB
    Config.Msi 0.00 MB 0.00 GB
    Documents and Settings 0.00 MB 0.00 GB
    Games 48522184491 46,274.36 MB 45.19 GB

    .EXAMPLE

    Get-FolderSize -BasePath 'C:\Program Files'
    -------------------------------------

    FolderName Size(Bytes) Size(MB) Size(GB)
    ---------- ----------- -------- --------
    7-Zip 4588532 4.38 MB 0.00 GB
    Adobe 3567833029 3,402.55 MB 3.32 GB
    Application Verifier 353569 0.34 MB 0.00 GB
    Bonjour 615066 0.59 MB 0.00 GB
    Common Files 489183608 466.52 MB 0.46 GB

    .EXAMPLE

    Get-FolderSize -BasePath 'C:\Program Files' -FolderName IIS
    -------------------------------------

    FolderName Size(Bytes) Size(MB) Size(GB)
    ---------- ----------- -------- --------
    IIS 5480411 5.23 MB 0.01 GB

    .EXAMPLE

    $getFolderSize = Get-FolderSize
    $getFolderSize | Format-Table -AutoSize
    -------------------------------------

    FolderName Size(GB) Size(MB)
    ---------- -------- --------
    Public 0.00 GB 0.00 MB
    thegn 2.39 GB 2,442.99 MB

    .EXAMPLE

    $getFolderSize = Get-FolderSize -Output csv -OutputPath ~\Desktop
    $getFolderSize
    -------------------------------------

    FolderName Size(GB) Size(MB)
    ---------- -------- --------
    Public 0.00 GB 0.00 MB
    thegn 2.39 GB 2,442.99 MB

    (Results will also be exported as a CSV to your Desktop folder)

    .EXAMPLE

    Sort by size descending
    $getFolderSize = Get-FolderSize | Sort-Object 'Size(Bytes)' -Descending
    $getFolderSize
    -------------------------------------

    FolderName Size(Bytes) Size(MB) Size(GB)
    ---------- ----------- -------- --------
    Users 76280394429 72,746.65 MB 71.04 GB
    Games 48522184491 46,274.36 MB 45.19 GB
    Program Files (x86) 27752593691 26,466.94 MB 25.85 GB
    Windows 25351747445 24,177.31 MB 23.61 GB

    .EXAMPLE

    Omit folder(s) from being included
    Get-FolderSize.ps1 -OmitFolders 'C:\Temp','C:\Windows'

    #>

    [cmdletbinding(
        DefaultParameterSetName = 'default'
    )]
    param(
        [Parameter(
            Mandatory = $false,
            Position = 0,
            ParameterSetName = 'default'
        )]
        [Alias('Path')]
        [String[]]
        $BasePath = (Get-Location),        

        [Parameter(
            Mandatory = $false,
            ParameterSetName = 'default'
            
        )]
        [Alias('User')]
        [String[]]
        $FolderName = 'all',

        [Parameter(
            ParameterSetName = 'default'
        )]
        [String[]]
        $OmitFolders,

        [Parameter(
            ParameterSetName = 'default'
        )]
        [Switch]
        $AddTotal,

        [Parameter(
            ParameterSetName = 'default'
        )]
        [Parameter(
            ParameterSetName = 'outputWithType'
        )]
        [ValidateSet('csv','xml','json')]
        [String]        
        $Output,

        [Parameter(
            ParameterSetName = 'default'
        )]
        [Parameter(
            ParameterSetName = 'outputWithType'
        )]
        [String]
        $OutputPath = (Get-Location),

        [Parameter(
            ParameterSetName = 'default'
        )]
        [String]
        $OutputFile = [string]::Empty
    )

    #Get a list of all the directories in the base path we're looking for.
    if ($folderName -eq 'all') {

        $allFolders = Get-ChildItem $BasePath -Directory -Force | Where-Object {$_.FullName -notin $OmitFolders}

    }
    else {

        $allFolders = Get-ChildItem $basePath -Directory -Force | Where-Object {($_.BaseName -like $FolderName) -and ($_.FullName -notin $OmitFolders)}

    }

    #Create array to store folder objects found with size info.
    [System.Collections.ArrayList]$folderList = @()

    #Go through each folder in the base path.
    ForEach ($folder in $allFolders) {

        #Clear out the variables used in the loop.
        $fullPath       = $null        
        $folderObject   = $null
        $folderSize     = $null
        $folderSizeInMB = $null
        $folderSizeInGB = $null
        $folderBaseName = $null

        #Store the full path to the folder and its name in separate variables
        $fullPath       = $folder.FullName
        $folderBaseName = $folder.BaseName     

        Write-Verbose "Working with [$fullPath]..."            

        #Get folder info / sizes
        $folderSize = Get-Childitem -Path $fullPath -Recurse -Force -ErrorAction SilentlyContinue | Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue       
            
        #We use the string format operator here to show only 2 decimals, and do some PS Math.
        $folderSizeInMB = "{0:N2} MB" -f ($folderSize.Sum / 1MB)
        $folderSizeInGB = "{0:N2} GB" -f ($folderSize.Sum / 1GB)

        #Here we create a custom object that we'll add to the array
        $folderObject = [PSCustomObject]@{

            FolderName    = $folderBaseName
            'Size(Bytes)' = $folderSize.Sum
            'Size(MB)'    = $folderSizeInMB
            'Size(GB)'    = $folderSizeInGB
            FullPath      = $fullPath

        }                        

        #Add the object to the array
        $folderList.Add($folderObject) | Out-Null

    }

    if ($AddTotal) {

        $grandTotal = $null

        if ($folderList.Count -gt 1) {
        
            $folderList | ForEach-Object {

                $grandTotal += $_.'Size(Bytes)'    

            }

            $totalFolderSizeInMB = "{0:N2} MB" -f ($grandTotal / 1MB)
            $totalFolderSizeInGB = "{0:N2} GB" -f ($grandTotal / 1GB)

            $folderObject = [PSCustomObject]@{

                FolderName    = 'GrandTotal'
                'Size(Bytes)' = $grandTotal
                'Size(MB)'    = $totalFolderSizeInMB
                'Size(GB)'    = $totalFolderSizeInGB
                FullPath      = 'N/A'

            }

            #Add the object to the array
            $folderList.Add($folderObject) | Out-Null
        }   

    }
    
    if ($Output -or $OutputFile) {

        if (!$OutputFile) {

            $fileName = "{2}\{0:MMddyy_HHmm}.{1}" -f (Get-Date), $Output, $OutputPath

        } else {

            $fileName = $OutputFile
            $Output   = $fileName.Substring($fileName.LastIndexOf('.') + 1) 


        }
       
        Write-Verbose "Attempting to export results to -> [$fileName]!"

        try {

            switch ($Output) {

                'csv' {
    
                    $folderList | Sort-Object 'Size(Bytes)' -Descending | Export-Csv -Path $fileName -NoTypeInformation -Force
    
                }
    
                'xml' {
    
                    $folderList | Sort-Object 'Size(Bytes)' -Descending | Export-Clixml -Path $fileName
    
                }
    
                'json' {
    
                    $folderList | Sort-Object 'Size(Bytes)' -Descending | ConvertTo-Json | Out-File -FilePath $fileName -Force
    
                }
    
            } 
        } 

        catch {

            $errorMessage = $_.Exception.Message

            Write-Error "Error exporting file to [$fileName] -> [$errorMessage]!"

        }
      
    }

    #Return the object array with the objects selected in the order specified.
    Return $folderList | Sort-Object 'Size(Bytes)' -Descending

}