Refreshing Icon Cache

by Jan 19, 2016

Sometimes, Windows Explorer does not show correct icons. When you update to PowerShell 5.0, for example, both PowerShell and PowerShell ISE got new and modern icons. If you still see the old icons, it may be time to refresh the icon cache.

Here is a function that can do this for you. It utilizes raw Windows API calls and forces the Windows Explorer to rebuild its icon cache.

function Update-ExplorerIcon {
  [CmdletBinding()]
  param()

  $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()

}

 

Throughout this month, we'd like to point you to three awesome community-driven global PowerShell events taking place this year:

Europe: April 20-22: 3-day PowerShell Conference EU in Hannover, Germany, with more than 30+ speakers including Jeffrey Snover and Bruce Payette, and 60+ sessions: www.psconf.eu.

Asia: October 21-22: 2-day PowerShell Conference Asia in Singapore. Watch latest announcements at www.psconf.asia

North America: April 4-6: 3-day PowerShell and DevOps Global Summit in Bellevue, WA, USA with 20+ speakers including many PowerShell Team members: https://eventloom.com/event/home/PSNA16

All events have limited seats available so you may want to register early.

Twitter This Tip! ReTweet this Tip!