Question

Writing a Powershell script that deletes all the contents from the recycle bins for virtual servers. For some reason I'm running into an error with finding the path for the Windows 2003 recycle bin and can't locate bin in order to delete everything in it. Was wondering if anyone here could give me some advice on what I am doing wrong with this code-snippet:

if($serverVersion.name -like '*2003*'){
$dir = "\\$server" + '\C$\recycled'
}
elseif($serverVersion.name -like '*2008*'){
$dir = "\\$server" + '\C$\$recycle.bin'
}

$recycleArray = @()
foreach ($item in get-childitem -path $dir){
    $recycleArray += $item
}

for ($i = 0; $i -le $recycleArray.length; $i++){
    $removal = $dir + "\" + $recycleArray[$i]
    remove-item $removal -force -recurse 
    }

I'm able to delete everything from the W2K8 recycle bin correctly so the code should work correctly once I'm able to find the path to the recycle bin. Here's a picture of the error message I receive for those curious in seeing:

enter image description here

Also, out of curiosity, is there a way to cut down all this code and make 2 one-liners for both 2003 and 2008? I realize that the current way I've written this out doesn't take advantage of Powershell's cmdlets and want to improve on it once I've figured out what's wrong with W2K3 recycle bin.

Was it helpful?

Solution

The problem is that the recycle bin is found on this location in widows server 2003 c:\recycler not c:\recycled so jsut change your code and it should work.

Try this code and see if it fixes the problem

if($serverVersion.name -like '*2003*'){
$dir = "\\$server" + '\C$\recycled'
}
elseif($serverVersion.name -like '*2008*'){
$dir = "\\$server" + '\C$\$recycle.bin'
}


foreach ($item in get-childitem -path $dir){
     remove-item $item.FullName -Force -Recurse
}

OTHER TIPS

So I run mine through powershell remoting like Invoke-Command or a local scheduled task instead of using UNC paths, and I just check all drives for either or 2003/2008 style recycle bins since the folder will appear on whatever drive the data was deleted from.This may or may not fit exactly what you are looking for but maybe it could help out.

$local_drives = Get-WmiObject Win32_LogicalDisk | Where-Object {$_.DriveType -eq 3}
foreach ($drive in $local_drives)
{
    $drive_letter = $drive.DeviceID
    $recycle_bins_03 = $drive_letter + '\RECYCLER'
    if (Test-Path $recycle_bins_03)
    {
        Get-ChildItem $recycle_bins_03 -Force | Remove-Item -Force -Recurse
    }
    $recycle_bins_08 = $drive_letter + '\$RECYCLE.BIN'
    if (Test-Path $recycle_bins_08)
    {
        Get-ChildItem $recycle_bins_08 -Force | Remove-Item -Force -Recurse
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top