Thursday, September 27, 2012

Emptying the Recycle Bin for a specific user

Suppose you want to empty the recycle bin of a different user but you do not know his password and do not want to reset it or just do not want to login with his account for any reason.

First get the SID of this account, use PsGetSid from PsTools
Then put the SID in the script below and run it. (will not delete until you uncomment the delete lines)


Const strRecycle = "\\$Recycle.Bin\\" 'Windows 2008, for Win7 use: \\Recycler\\
Set objSWbemServices = GetObject _
    ("WinMgmts:Root\Cimv2")

Dim SIDs : SIDs = Array("S-1-5-21-4040636791-1997804162-1132720628-1008",_
   "S-1-5-21-4040636791-1997804162-1132720628-1014",_
   "S-1-5-21-4040636791-1997804162-1132720628-1018")


For Each sid In SIDs

    Set colDisks = objSWbemServices.ExecQuery _
        ("Select * From Win32_LogicalDisk " &  "Where DriveType = 3")

    For Each objDisk In colDisks
        Set colDeletedFiles = objSWbemServices.ExecQuery _
        ("Select * From Cim_DataFile Where Drive = '" _
        & objDisk.DeviceId _
        & "' And Path = '" & strRecycle & sid & "
\\' " _
        & "And Hidden = False")

        For Each objDeletedFile In colDeletedFiles
            WScript.Echo objDeletedFile.Name
            'objDeletedFile.Delete
        Next
       
        Set colDeletedFolders = objSWbemServices.ExecQuery _
        ("Select * From Win32_Directory Where Drive = '" _
        & objDisk.DeviceId _
        & "' And Path = '" & strRecycle & sid & "
\\' " _
        & "And Hidden = False")

        For Each objDeletedFolder In colDeletedFolders
            WScript.Echo objDeletedFolder.Name
            'objDeletedFolder.Delete
        Next

    Next
Next

4 comments:

  1. Can you explain how this would work without having to uncomment the delete lines

    ReplyDelete
  2. Which comments should I remove? Which ones are the delete lines? Can you put the code up where all I have to do is add the SID?

    ReplyDelete
  3. Hello,

    uncomment line 20
    remove the single quote character ' before objDeletedFile.Delete

    ReplyDelete
  4. OK, thanks it is working now but there is a problem with the script and how it deletes content from multiple recycle bins. If I have multiple users/SID's which have logged onto the computer then this means I have multiple recycle bins. If I run the script against only ONE of the SID's all the recycle bins get emptied. This is on a Win7 system. ANy ideas?

    ReplyDelete