简体   繁体   English

使用Powershell以编程方式清除回收站

[英]Clear Recycle Bin programmatically with Powershell

One of the hardest things I've had to do is access Windows APIs with PowerShell. 我必须做的最困难的事情之一是使用PowerShell访问Windows API。 I want to erase the Recycle Bin using the API in Shell32.dll. 我想使用Shell32.dll中的API擦除回收站。 There are other ways of doing it, but they are typically bypassing the normal Windows processes and in this case, I want to do it the "right" way. 还有其他方法,但它们通常绕过正常的Windows进程,在这种情况下,我想以“正确”的方式做到这一点。

After a few hours, I came up with this. 几个小时后,我想出了这个。

$TypeDefinition=@"
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace shell32 {

    //Put all the variables required for the DLLImports here
    enum RecycleFlags : uint { SHERB_NOCONFIRMATION = 0x00000001, SHERB_NOPROGRESSUI = 0x00000002, SHERB_NOSOUND = 0x00000004 }

    public static class RecycleBin {
        [DllImport("Shell32.dll",CharSet=CharSet.Unicode)]
            internal static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags);
    }

    public class ShellWrapper : IDisposable {

        // Creates a new wrapper for the local machine
        public ShellWrapper() { }

        // Disposes of this wrapper
        public void Dispose() {
            GC.SuppressFinalize(this);
        }

        //Put public function here
        public uint Empty() {
            uint ret = RecycleBin.SHEmptyRecycleBin(IntPtr.Zero, null, RecycleFlags.SHERB_NOCONFIRMATION | RecycleFlags.SHERB_NOPROGRESSUI | RecycleFlags.SHERB_NOSOUND);
            return ret;
        }

        // Occurs on destruction of the Wrapper
        ~ShellWrapper() {
            Dispose();
        }

    } //Wrapper class
}
"@
Add-Type -TypeDefinition $TypeDefinition -PassThru | out-null
$RecycleBin=new-object Shell32.ShellWrapper

$RecycleBin.Empty()

How about this? 这个怎么样? Does not reset any permissions, works for all users and across all drives. 不重置任何权限,适用于所有用户和所有驱动器。 I tested it on 2012 R2+ 我在2012 R2 +上测试了它

$dis = gwmi Win32_LogicalDisk -Filter 'DriveType=3' | select -ExpandProperty DeviceID
$rec = @()

foreach ($d in $dis)
{
    $rec += gci "$d\`$Recycle.Bin" -Force
}


foreach ($r in $rec)
{
    gci $r.FullName -Force -Recurse | rm -Force -Confirm:$false
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM