Monday, July 25, 2011

PowerShell Scripts and Cmdlets - Part 1

I have to admit I am a newcomer to PowerShell - definitely late to the party, and probably not fashionably late, either. But I decided to dig into it since I had to write a PS script as part of a project at work. And after that I decided I wouldn't just leave it at that, but use this as an opportunity to pick up another platform to add to my resume. So I wrote out a list of things I want to learn and am picking them off one by one.

1. Write a script
2. Write a cmdlet
3. Write a script using Exchange Management shell
4. Write a script that uses the SharePoint object model
5. Write a script that interacts with AD, WMI, other?

The first thing on my list is writing a PS script. I wrote a script to move files off of various servers onto a central server into a structured hierarchy of folders. The script employed some interesting bits, like an XML configuration file, command-line syntax help, working with files and directories and even displaying progress via the Write-Progress cmdlet. Nothing overly complicated, but it was a good way to get introduced to PS. I also wrote a script to create test data to test my script. In writing that script, I discovered that PS has no cmdlet akin to the Unix touch command. Segue into my next task.

For my cmdlet task, I decided to write a command that can update the last modified timestamp of a file or group of files. My idea is to have this follow the conventions of the Unix touch command. Except for the name. Powershell has it's own naming convention that uses a verb-noun pair for naming commands. To stick with this convention, I decided to go with "touch-item" as the name of my cmdlet.

I won't go into the minute details of how you write a cmdlet, but the basics are you create a class that inherits the Cmdlet class, add an attribute specific to Powershell that defines the name of the cmdlet (i.e. touch-item, in my case), and then override some methods to provide the cmdlet's processing. For my development environment, I decided to use VisualStudio 2010 and targeting the .NET Framework 3.5.