[英]Clear Recycle Bin programmatically with Powershell
我必須做的最困難的事情之一是使用PowerShell訪問Windows API。 我想使用Shell32.dll中的API擦除回收站。 還有其他方法,但它們通常繞過正常的Windows進程,在這種情況下,我想以“正確”的方式做到這一點。
幾個小時后,我想出了這個。
$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()
這個怎么樣? 不重置任何權限,適用於所有用戶和所有驅動器。 我在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.