As much as I love a clean desktop, I know it is impossible to let it remain uncluttered for long.

Image of a messy desktopFlickr: Josh Swannack / Messy Desktop

One strategy I started using to keep the desktop clean was to cut and paste all loose files into a folder named ORG from time to time. This way I would know where to go when I needed that one file I saved somewhere.

Since I am now using the awesome PowerShell v2, I wrote script to do this for me automatically.

$dirtyfolder = "C:\Documents and Settings\banimesh\Desktop\"
$org = "$dirtyfolder\ORG"


ls "$($dirtyfolder)/*" | ? {!$_.PSIsContainer} | %{
  $dest = "$($org)\$($_.extension)"
  if (! (Test-Path -path $dest ) ) 
  {
    write-host "creating $dest"
    new-item $dest -type directory
  }
  mv -path $_ -destination $dest 
}

This solution felt equivalent to shoving all your clutter under the bed since the mess, as a unit, was simply moved to another location.

So I decided to organize the clutter by file extension. I have updated the above piece of code to do that as follows.

ls $dirtyfolder/* | ? {!$_.PSIsContainer} | %{
  $dest = "$($org)ORG\$($_.extension)"
  if (! (Test-Path -path $dest ) ) {
    new-item $dest -type directory
  }
  mv -path $_.fullname -destination $dest 
}

This was good but the number of folders inside the ORG folder was too many for the solution to be of any use to me.

So I tinkered around with grouping by file category and came up with the below solution.

function get-destbytype($ext) 
{
    switch ($ext)
    {
        { $ext -match '(jpg|png|gif|bmp)'} { "images" }
        { $ext -match '(divx|mpeg|avi)'} { "videos" }
        { $ext -match '(cs|js|java|py|class|vbs|jsp)'} { "code" }
        { $ext -match '(sql|ps1|pl|py)'} { "scripts" }
        { $ext -match '(zip|7z|rar)'} { "compressed" }
        { $ext -match '(ppt|pptx|doc|docx|pdf)'} { "documents" }
        { $ext -match '(csv|xls|xlsx)'} { "spreadsheets" }
        { $ext -match '(exe|dll|jar|ear|bat|cmd)'} { "executables" }
        { $ext -match '(txt|log)'} { "text" }
        { $ext -match '(vm|msg|htm|html|lnk)'} { "miscellaneous" }
        { $ext -match '(properties|xml|ini)'} { "config" }
        default {"$ext" }
    }
}

$dirtyfolder = "C:\Documents and Settings\banimesh\Desktop\"
$org = "$C:\Documents and Settings\banimesh\Desktop\ORG"


ls $dirtyfolder/* | ? {!$_.PSIsContainer} | %{
  $dest = "$($org)\$(get-destbytype $_.extension)"
  if (! (Test-Path -path $dest ) ) 
  {
    write-host "creating $dest"
    new-item $dest -type directory
  }
  mv -path $_ -destination $dest 
}

One bug I found in this was that .cs and .csv are moved to a single folder. I will fix it later.

The opposite of this script is now available.