Skip to content

Instantly share code, notes, and snippets.

@bitsydoge
Created May 16, 2023 18:22
Show Gist options
  • Save bitsydoge/19509d204fdda10ea4a1fee90186f43a to your computer and use it in GitHub Desktop.
Save bitsydoge/19509d204fdda10ea4a1fee90186f43a to your computer and use it in GitHub Desktop.
param(
[Parameter(Mandatory=$true)]
[string]
$rootDirectory,
[Parameter(Mandatory=$true)]
[string]
$filePattern,
[Parameter(Mandatory=$false)]
[switch]
$displayFiles
)
# Get all files that match the specified pattern
$filesToDelete = Get-ChildItem -Path $rootDirectory -Filter $filePattern -Recurse
# Check if any files are found
if ($filesToDelete.Count -eq 0) {
Write-Host "No files matching the specified pattern found."
return
}
# Display the number of files found
Write-Host "Found $($filesToDelete.Count) files matching the specified pattern."
if ($displayFiles) {
Write-Host "The following files will be deleted:"
foreach ($file in $filesToDelete) {
Write-Host $file.FullName
}
}
$confirmation = Read-Host "Are you sure you want to delete these files? (Y/N)"
# If confirmed, delete the files
if ($confirmation -eq "Y" -or $confirmation -eq "y") {
$deletedCount = 0
$failedCount = 0
foreach ($file in $filesToDelete) {
try {
Remove-Item -Path $file.FullName -Force -ErrorAction Stop
$deletedCount++
} catch {
$failedCount++
}
}
Write-Host "Files deleted successfully: $deletedCount"
Write-Host "Files failed to delete: $failedCount"
} else {
Write-Host "Deletion canceled."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment