My First Powershell Script

| No Comments

I wrote my first useful Powershell script today. I had a directory of bitmaps and I wanted to convert them to PNG. This is a relatively easy task in .NET. All I had to do was figure out how to do this within Powershell. The script is as such:


foreach($file in Get-ChildItem *.BMP)
{
echo $file.Name
$image = [System.Drawing.Image]::FromFile($file)
$image.Save($file.ToString().Replace("BMP","png"), [System.Drawing.Imaging.ImageFormat]::Png)
}

As simple as this may seem, it really isn't. First, the FromFile() method kept throwing an exception with NO description. After running FileMon did I see that it was looking in the wrong place for the file. As to why it didn't bubble up a FileNotFoundException, I haven't a clue (thanks Redmond). I also attempted to trap the exception, but seems to do nothing as well.

The second hurdle to get past was the fact that Get-ChildItem returns a System.IO.FileInfo type and the Name property contains only that -- no full path. However ToString() does, and so that is where I called Replace() on. Once the pieces where in place, it worked like a charm.

Leave a comment

Bookmark and Share
Powered by Movable Type 5.02

Twitter Updates

    Follow me on Twitter

    About this Entry

    This page contains a single entry by DrFooMod2 published on May 2, 2007 2:59 PM.

    Teletype Bluetooth GPS Receiver on my BlackBerry 8700 was the previous entry in this blog.

    TeleNav and my New 8800 is the next entry in this blog.

    Find recent content on the main index or look in the archives to find all content.