Skip to content

Instantly share code, notes, and snippets.

@whit3rabbit
Created March 20, 2023 00:38
Show Gist options
  • Select an option

  • Save whit3rabbit/22d671a44d945a3d124e0b914bf93e5d to your computer and use it in GitHub Desktop.

Select an option

Save whit3rabbit/22d671a44d945a3d124e0b914bf93e5d to your computer and use it in GitHub Desktop.
remove duplicates files from current directoy
# Function to display a menu and get the user's choice
function Show-Menu {
param (
[string]$Title = "Menu",
[string[]]$MenuItems
)
Clear-Host
# Display the title
Write-Host $Title
Write-Host "=" * $Title.Length
Write-Host ""
# Display the menu items
for ($i = 0; $i -lt $MenuItems.Length; $i++) {
Write-Host $MenuItems[$i]
}
Write-Host ""
# Get the user's choice
$choice = Read-Host "Enter your choice (1-$($MenuItems.Length))"
# Validate the user's choice
if ($choice -match '^\d+$' -and $choice -ge 1 -and $choice -le $MenuItems.Length) {
return $choice
} else {
Write-Host "Invalid choice. Please enter a number between 1 and $($MenuItems.Length)."
Pause
return 0
}
}
# Get the current directory
$currentDirectory = Get-Location
# Define the menu items
$menuItems = @(
"1. Generate list of duplicate files",
"2. Delete files in duplicate list"
)
# Display the menu and get the user's choice
$menuChoice = Show-Menu -Title "File Management Menu" -MenuItems $menuItems
# Process the user's choice
switch ($menuChoice) {
1 {
# Get all files in the current directory
$files = Get-ChildItem -Path $currentDirectory -File -Recurse
# Group files by name
$groups = $files | Group-Object -Property Name -AsHashTable
# Get all files with more than one file in the group
$duplicates = $groups.GetEnumerator() | Where-Object { $_.Value.Count -gt 1 }
# If there are no duplicates, display a message and exit
if ($duplicates.Count -eq 0) {
Write-Host "No duplicate files found."
break
}
# Create a text file with the duplicate names
$duplicateList = "DuplicateFiles.txt"
$duplicates.Keys | Out-File $duplicateList
# Display the duplicate names
Write-Host "Duplicate files found:"
$duplicates.Keys | ForEach-Object { Write-Host $_ }
}
2 {
# Check if the duplicate list file exists
$duplicateList = "DuplicateFiles.txt"
if (!(Test-Path $duplicateList)) {
Write-Host "No files to delete."
break
}
# Display the file names and ask the user if they want to delete them
$filesToDelete = Get-Content $duplicateList
Write-Host "Files to delete:"
$filesToDelete | ForEach-Object { Write-Host $_ }
$deleteFiles = Read-Host "Do you want to delete these files? (Y/N)"
# If the user wants to delete the files, remove each file
if ($deleteFiles.ToUpper() -eq "Y") {
foreach ($file in $filesToDelete) {
Remove-Item $file -Force
}
# Remove the duplicate list file
Remove-Item $duplicateList -Force
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment