-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemove-DotNetBuildArtifact.ps1
More file actions
370 lines (311 loc) · 14.1 KB
/
Copy pathRemove-DotNetBuildArtifact.ps1
File metadata and controls
370 lines (311 loc) · 14.1 KB
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
365
366
367
368
369
370
function Remove-DotNetBuildArtifact
{
<#
.SYNOPSIS
Removes bin and obj folders from .NET project directories with optional recursion.
.DESCRIPTION
Searches for .NET project files (.csproj, .vbproj, .fsproj, .sqlproj) and removes their
associated bin and obj build artifact folders. Only removes folders when a project file is
found in the parent directory, similar to 'dotnet clean' but more thorough. Recursion is
controlled by the -Recurse switch.
Cross-platform compatible with PowerShell 5.1+ on Windows, macOS, and Linux.
.PARAMETER Path
The root path to search for .NET projects. Defaults to the current directory.
Supports ~ for home directory expansion.
.PARAMETER ExcludeDirectory
Array of directory names to exclude from the search. Defaults to @('.git', 'node_modules').
These directories and their subdirectories will not be searched for .NET projects.
.PARAMETER NoSizeCalculation
Skips calculating the size of folders before removal. By default, folder sizes are calculated
to provide detailed space freed information. Use this switch for large directory structures
to significantly speed up execution.
.PARAMETER Recurse
When specified, searches for projects in subdirectories. Without this switch, only the
specified path is inspected.
.PARAMETER WhatIf
Shows what would be removed without actually removing anything.
.PARAMETER Confirm
Prompts for confirmation before removing each folder.
.EXAMPLE
PS > Remove-DotNetBuildArtifact -Recurse
Removes bin and obj folders from .NET projects in the current directory and subdirectories,
showing the total space freed.
.EXAMPLE
PS > Remove-DotNetBuildArtifact -NoSizeCalculation
Removes build artifacts without calculating space freed (faster for large directory structures).
.EXAMPLE
PS > Remove-DotNetBuildArtifact -Path ~/Projects -Recurse -WhatIf
Shows what would be removed in the ~/Projects directory and its subdirectories without actually removing anything.
.EXAMPLE
PS > Remove-DotNetBuildArtifact -Path C:\MyProjects -Recurse -Confirm
Removes build artifacts with confirmation prompts for each folder.
.EXAMPLE
PS > Remove-DotNetBuildArtifact -Verbose
Removes build artifacts with detailed verbose output showing each operation.
.EXAMPLE
PS > Remove-DotNetBuildArtifact -Path ~/Projects -ExcludeDirectory @('.git', 'node_modules', 'vendor')
Removes build artifacts while excluding .git, node_modules, and vendor directories from the search.
.OUTPUTS
[PSCustomObject]
Returns an object with summary information about the operation:
- TotalProjectsFound: Number of .NET projects discovered
- FoldersRemoved: Number of folders successfully removed
- TotalSpaceFreed: Total disk space freed (unless -NoSizeCalculation is specified)
- Errors: Number of errors encountered
.LINK
https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-clean
.NOTES
- Requires PowerShell 5.1 or later
- Only removes bin/obj folders when a .NET project file exists in the parent directory
- Respects -WhatIf and -Confirm parameters for safety
- Processes .csproj, .vbproj, .fsproj, and .sqlproj project files
Author: Jon LaBelle
License: MIT
Source: https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Developer/Remove-DotNetBuildArtifact.ps1
.LINK
https://github.com/jonlabelle/pwsh-profile/blob/main/Functions/Developer/Remove-DotNetBuildArtifact.ps1
#>
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '')]
[CmdletBinding(SupportsShouldProcess)]
[OutputType([PSCustomObject])]
param(
[Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[String]$Path = (Get-Location).Path,
[Parameter()]
[String[]]$ExcludeDirectory = @('.git', 'node_modules'),
[Parameter()]
[Switch]$NoSizeCalculation,
[Parameter()]
[Switch]$Recurse
)
begin
{
Write-Verbose 'Starting .NET build artifacts cleanup'
# Statistics tracking
$stats = @{
ProjectsFound = 0
FoldersRemoved = 0
TotalSpaceFreed = [int64]0
Errors = 0
}
# Project file patterns (single source of truth)
$projectPatterns = @('*.csproj', '*.vbproj', '*.fsproj', '*.sqlproj')
$projectExtensions = $projectPatterns | ForEach-Object {
$_.Substring(1).ToLowerInvariant()
}
# Log excluded directories
if ($ExcludeDirectory -and $ExcludeDirectory.Count -gt 0)
{
Write-Verbose "Excluding directories: $($ExcludeDirectory -join ', ')"
}
}
process
{
try
{
# Resolve and validate the path
$resolvedPath = $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
if (-not (Test-Path -Path $resolvedPath -PathType Container))
{
Write-Error "Path not found or is not a directory: $resolvedPath"
return
}
Write-Verbose "Searching for .NET projects in: $resolvedPath"
# Build Get-ChildItem parameters (filtering by extension after retrieval for reliability across PS versions)
$getChildItemParams = @{
Path = $resolvedPath
File = $true
ErrorAction = 'SilentlyContinue'
}
if ($Recurse.IsPresent)
{
$getChildItemParams.Recurse = $true
}
# Disable progress bar for recursive file search (PowerShell 7.4+)
if ($PSVersionTable.PSVersion.Major -ge 7 -and $PSVersionTable.PSVersion.Minor -ge 4)
{
$getChildItemParams['ProgressAction'] = 'SilentlyContinue'
}
# Helper to check excluded directories in a path
function Test-IsExcludedPath
{
param(
[String]$FilePath,
[String[]]$ExcludedDirs
)
foreach ($excludeDir in $ExcludedDirs)
{
$escaped = [regex]::Escape([System.IO.Path]::DirectorySeparatorChar + $excludeDir + [System.IO.Path]::DirectorySeparatorChar)
$escapedEnd = [regex]::Escape([System.IO.Path]::DirectorySeparatorChar + $excludeDir + '$')
if ($FilePath -match $escaped -or $FilePath -match $escapedEnd)
{
return $true
}
}
return $false
}
$allProjectFiles = Get-ChildItem @getChildItemParams
# Filter by project extensions and exclusions
$projectFiles = $allProjectFiles | Where-Object {
$ext = $_.Extension.ToLowerInvariant()
$isProject = $ext -in $projectExtensions
if (-not $isProject)
{
return $false
}
if ($ExcludeDirectory -and $ExcludeDirectory.Count -gt 0)
{
return -not (Test-IsExcludedPath -FilePath $_.FullName -ExcludedDirs $ExcludeDirectory)
}
return $true
}
if (-not $projectFiles -or $projectFiles.Count -eq 0)
{
Write-Host 'No .NET project files found in the specified path.' -ForegroundColor Yellow
return
}
$stats.ProjectsFound = $projectFiles.Count
Write-Host "Found $($stats.ProjectsFound) .NET project(s)" -ForegroundColor Cyan
# Process each project
foreach ($projectFile in $projectFiles)
{
$projectDir = $projectFile.DirectoryName
Write-Verbose "Processing project: $($projectFile.Name) in $projectDir"
# Look for bin and obj folders in the project directory
$artifactFolders = @('bin', 'obj') | ForEach-Object {
$folderPath = Join-Path -Path $projectDir -ChildPath $_
if (Test-Path -Path $folderPath -PathType Container)
{
Get-Item -Path $folderPath
}
}
# Remove the artifact folders
foreach ($folder in $artifactFolders)
{
if ($folder)
{
try
{
# Calculate folder size before removal (unless disabled)
$folderSize = [int64]0
if (-not $NoSizeCalculation)
{
try
{
$getSizeParams = @{
Path = $folder.FullName
Recurse = $true
File = $true
ErrorAction = 'SilentlyContinue'
}
# Disable progress bar when calculating folder size
if ($PSVersionTable.PSVersion.Major -ge 7 -and $PSVersionTable.PSVersion.Minor -ge 4)
{
$getSizeParams['ProgressAction'] = 'SilentlyContinue'
}
$folderSize = (Get-ChildItem @getSizeParams |
Measure-Object -Property Length -Sum -ErrorAction SilentlyContinue).Sum
if ($null -eq $folderSize) { $folderSize = 0 }
}
catch
{
Write-Verbose "Could not calculate size for: $($folder.FullName)"
$folderSize = 0
}
}
if ($PSCmdlet.ShouldProcess($folder.FullName, 'Remove build artifact folder'))
{
# Remove the folder
$removeParams = @{
Path = $folder.FullName
Recurse = $true
Force = $true
ErrorAction = 'Stop'
}
# Disable progress bar during recursive folder deletion
if ($PSVersionTable.PSVersion.Major -ge 7 -and $PSVersionTable.PSVersion.Minor -ge 4)
{
$removeParams['ProgressAction'] = 'SilentlyContinue'
}
Remove-Item @removeParams
Write-Host "Removed: $($folder.FullName)" -ForegroundColor Green
$stats.FoldersRemoved++
$stats.TotalSpaceFreed += $folderSize
}
else
{
Write-Host "WhatIf: Would remove $($folder.FullName)" -ForegroundColor Yellow
$stats.TotalSpaceFreed += $folderSize
}
}
catch
{
$stats.Errors++
Write-Warning "Failed to remove $($folder.FullName): $($_.Exception.Message)"
Write-Verbose "Error details: $($_.Exception)"
}
}
}
}
}
catch
{
$stats.Errors++
Write-Error "Error processing path: $($_.Exception.Message)"
Write-Verbose "Error details: $($_.Exception)"
}
}
end
{
# Helper function to format bytes into human-readable size
function Format-ByteSize
{
param([int64]$Bytes)
switch ($Bytes)
{
{ $_ -ge 1TB } { '{0:N2} TB' -f ($_ / 1TB); break }
{ $_ -ge 1GB } { '{0:N2} GB' -f ($_ / 1GB); break }
{ $_ -ge 1MB } { '{0:N2} MB' -f ($_ / 1MB); break }
{ $_ -ge 1KB } { '{0:N2} KB' -f ($_ / 1KB); break }
default { '{0} bytes' -f $_ }
}
}
# Format space freed for output and return object
$spaceFreedFormatted = if (-not $NoSizeCalculation)
{
if ($stats.TotalSpaceFreed -gt 0)
{
Format-ByteSize -Bytes $stats.TotalSpaceFreed
}
else
{
'0 bytes'
}
}
else
{
'Not calculated (use without -NoSizeCalculation for details)'
}
# Display summary
Write-Host "`nCleanup Summary:" -ForegroundColor Cyan
Write-Host " Projects found: $($stats.ProjectsFound)" -ForegroundColor White
Write-Host " Folders removed: $($stats.FoldersRemoved)" -ForegroundColor White
if (-not $NoSizeCalculation -and $stats.TotalSpaceFreed -gt 0)
{
Write-Host " Space freed: $spaceFreedFormatted" -ForegroundColor Green
}
if ($stats.Errors -gt 0)
{
Write-Host " Errors: $($stats.Errors)" -ForegroundColor Red
}
Write-Verbose 'Cleanup completed'
# Return statistics object
return [PSCustomObject]@{
TotalProjectsFound = $stats.ProjectsFound
FoldersRemoved = $stats.FoldersRemoved
TotalSpaceFreed = $spaceFreedFormatted
Errors = $stats.Errors
}
}
}