Using Powershell to Find Unused Images on my Site

I developed the following Powershell code to help me isolate images in my website's "images" folder that were not being used by the site code:

$image_folder_mask = ".\website\images\*"
$source_file_mask = ".\website\*.aspx",".\website\*.cs",".\website\*.ascx",".\website\*.master",".\website\styles\*.css"

$image_list = new-object system.collections.arraylist
$image_list.addrange(@(get-item -path $image_folder_mask -include "*.png","*.gif","*.jpg" | select name))

foreach($file in get-item $source_file_mask)
{
   foreach($text in $(get-content $file.fullname))
   {
      #echo $text

      if($text -match "[a-z0-9_]+\.png|[a-z0-9_]+\.gif|[a-z0-9_]+\.jpg")
      {
         foreach($current_match in $matches)
         {
            $searcher = $current_match[0]

            for($i = 0; $i -lt $image_list.count; $i++)
            {
               $searchee = $image_list[$i]

               if($searchee.name.trim() -eq $searcher.trim())
               {
                  $image_list.removeat($i)
               }
            }
         }
      }
   }
}

echo $image_list

1 comments :: Using Powershell to Find Unused Images on my Site

  1. Fixed to include "-" in file names:

    $image_folder_mask = ".\images\*",".\images\Buttons\*"
    $source_file_mask = ".\*.aspx",".\*.js",".\*.cs",".\*.ascx",".\*.master",".\styles\*.css"

    $image_list = new-object system.collections.arraylist
    $image_list.addrange(@(get-item -path $image_folder_mask -include "*.png","*.gif","*.jpg" | select name))

    foreach($file in get-item $source_file_mask)
    {
    foreach($text in $(get-content $file.fullname))
    {
    #echo $text

    if($text -match "[a-z0-9_\-]+\.png|[a-z0-9_\-]+\.gif|[a-z0-9_\-]+\.jpg")
    {
    foreach($current_match in $matches)
    {
    $searcher = $current_match[0]

    for($i = 0; $i -lt $image_list.count; $i++)
    {
    $searchee = $image_list[$i]

    if($searchee.name.trim() -eq $searcher.trim())
    {
    $image_list.removeat($i)
    }
    }
    }
    }
    }
    }

    echo $image_list