For anyone finding this thread, here's a related thread which has some other methods of doing similar things.
The script I posted above is a good solution for some tasks, but the ones in the other thread may suit you better, depending on exactly what you need to do.