Adventures in PowerShell part 1 - Desktop Cleaning

Tuesday, February 19 2008

I’ve been interested in PowerShell for ages but haven’t put any serious time into it. About a year ago I installed it and started playing around, liked it but didn’t do anything really useful. I bought Bruce Payette’s Windows PowerShell in Action, which is excellent and I highly recommend it around then, and ran through the examples. I got what was possible with PowerShell, but I learn best by doing – and I really didn’t have anything I needed to build so the information didn’t really sink in.

This week I decided to revisit it and see what I could do. My interest was rekindled by listening to the .NET Rocks show with Kirk Munro which was a good explanation of the technology and an introduction to the free PowerGUI tool.

So I had another crack at writing PowerShell, I started with FizzBuzz (too easy), then moved on to replacing a .vbs script I’ve been using for a while.

I like a clean Windows desktop, I keep it clear of any program icons but I do use it to store any recent downloads or for keeping documents I’ve recently been sent. Unfortunately it means my desktop fills up pretty quick so I built a script that archives everything on my desktop to a Cleanup directory tree. So a word document will end up in C:\cleanup\doc and a Zip will go to C:\cleanup\zip etc. It works for me, I know where to look based on the type of document. Periodically I go through these folders and delete what  I don’t need, and move things I do need to a proper home.

I had a vbs script for doing this that worked fine, I have it run as a scheduled task when I log on. In VBScript this is about 25 lines of code ( I like to keep my code readable, if I can use 5 lines instead of 3 I will, so you could do it in fewer lines).

In PowerShell it’s much simpler.

$indir = Get-Item C:\Users\Damian\Desktop
$outdir = Get-Item C:\Cleanup\

foreach ($f in dir $indir) 
{
	if ( $f.Extension.length -gt 0 ) 
	{ 
		$strpath = "C:\cleanup\" + $f.Extension.Substring(1)
		if ( -not $(Test-Path -literalpath ($strpath)) )
		{
			New-Item -ItemType Directory -Path $strpath | Out-Null
		}
		$cpdir = Get-Item $strpath
		Get-Item ($f.Directory.ToString() + "\" + $f.ToString()) | move -Destination $cpdir
	}
}

I’m sure there is a better way to get some of the directories rather than joining strings, but this works nicely.

I plan on digging up a lot of the little utility scripts I’ve written over the years and converting them to PowerShell, I think it’s a very nice technology but the only way to really get it is just dig in and do it.