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.

Comments are closed.