Question:
I have created a powershell script that listens for files to be created on the desktop. The file is immediately deleted if it meets certain criteria. I used Remove-Item $path
where $path
is the path to the file I want to delete. The problem is that windows still adds, and continues to show the item on the desktop. The file is definitely not there, since attempting to manipulate it will result in a ‘Could not find this item’, or ‘File does not exist’ error. Manually refreshing the desktop via ‘Right Click => Refresh’ will cause the item to be removed.
Is there a way to force the desktop to refresh after deleting an item on it? Otherwise, is there an alternate method to delete the file to prevent it being added in the first place?
Answer:
ou can use the SHChangeNotify from Shell32.dll
You’ve got a function in former PowerShell.com, no longer available
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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() } |