PowerShell/Microsoft/Empty_recycle_bin.ps1

73 lines
1.9 KiB
PowerShell

# Script by Timur@0x01337.com
# Date: 2023-11-24
<#
.DESCRIPTION
Deletes the files from recycle bin on the specified drive. If no arguments are specified, deletes the files from recycle bin on the C drive.
If script is launched for LocalSystem account, then contents of 'C:\$Recycle.Bin\S-1-5-18' folder will be cleared. This folder does not appear on Desktop.
.PARAMETER driveletter
Optional. A letter of the drive which recycle bin will be emptied. Default is the C drive.
.PARAMETER help
Displays a detailed usage description of this script.
.EXAMPLE
PS> .\Empty-Recycle-Bin.ps1
.EXAMPLE
PS> .\Empty-Recycle-Bin.ps1 -driveletter C
.EXAMPLE
PS> .\Empty-Recycle-Bin.ps1 -help
#>
# Getting command line parameters
param (
[parameter(Mandatory = $false)][string]$driveletter = "C",
[parameter(Mandatory = $false)][switch]$help
)
# Writing help message
if ($help) {
get-help $MyInvocation.MyCommand.Path -Full
exit 0
}
if ($driveletter) {
try {
$drive = Get-Volume -DriveLetter $driveletter -ErrorAction Stop
}
catch {
Write-Error "$driveletter drive is not found"
exit 1
}
if ($drive.DriveType -ne "Fixed") {
Write-Error "Drive $driveletter is not fixed drive, can't find recycle bin in it"
exit 1
}
}
$path = '$Recycle.bin'
$path = "$($driveletter):\$path"
Write-Host "Clearing recycle bins on the $driveletter drive"
$bins = $null
$bins = Get-ChildItem -Path $path -Force -ErrorAction SilentlyContinue
foreach ($bin in $bins) {
$items = $null
$items = Get-ChildItem -Path "$path\$bin" -Force -ErrorAction SilentlyContinue
if ($items) {
Write-Host "Clearing recycle bin $path\$bin"
foreach ($item in $items) {
Remove-Item -Path "$path\$bin\$item" -Force -Recurse -ErrorAction SilentlyContinue
}
}
}
Write-Host "Finished clearing the recycle bin"
exit 0