我创建了一个 powershell 脚本,用于侦听要在桌面上创建的文件。如果文件满足特定条件,则会立即删除该文件。我使用Remove-Item $pathwhere$path是我要删除的文件的路径。问题是 windows 仍然添加,并继续在桌面上显示该项目。该文件肯定不存在,因为尝试操作它会导致“找不到此项目”或“文件不存在”错误。通过“右键单击 => 刷新”手动刷新桌面将导致该项目被删除。
有没有办法在删除桌面上的项目后强制刷新桌面?否则,是否有其他方法可以删除文件以防止首先添加它?
对于仍在寻找答案的任何人,我也会在这里重新发布我对这个问题的回答,因为 PowerShel.com 的链接似乎不再有效:
我使用以下代码通过 C# 代码从 powershell 调用桌面上的刷新:
$code = @'
[System.Runtime.InteropServices.DllImport("Shell32.dll")]
private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);
public static void Refresh() {
SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero);
}
'@
Add-Type -MemberDefinition $code -Namespace WinAPI -Name Explorer
[WinAPI.Explorer]::Refresh()
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助任何仍在寻找答案的人。
您可以使用Shell32.dll 中的SHChangeNotify
您在以前的PowerShell.com中有一个功能,不再可用
function Refresh-Explorer {
$code = @'
private static readonly IntPtr HWND_BROADCAST = new IntPtr(0xffff);
private const int WM_SETTINGCHANGE = 0x1a;
private const int SMTO_ABORTIFHUNG = 0x0002;
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern bool SendNotifyMessage(IntPtr hWnd, uint Msg, UIntPtr wParam,
IntPtr lParam);
[System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SendMessageTimeout ( IntPtr hWnd, int Msg, IntPtr wParam, string lParam, uint fuFlags, uint uTimeout, IntPtr lpdwResult );
[System.Runtime.InteropServices.DllImport("Shell32.dll")]
private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);
public static void Refresh() {
SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero);
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, IntPtr.Zero, null, SMTO_ABORTIFHUNG, 100, IntPtr.Zero);
}
'@
Add-Type -MemberDefinition $code -Namespace MyWinAPI -Name Explorer
[MyWinAPI.Explorer]::Refresh()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6502 次 |
| 最近记录: |