Wednesday, January 11, 2012

Powershell (v2) - Changing File Extensions on All Files in a Folder

In a current work project we had a customer send us a ton of .tif images without extensions. After viewing the files binary data, I was able to identify they were in fact .tif files. To add extensions to these files I went searching for a script to help. After some hunting I ran across a PowerTip that got the job done.
Bulk-Changing File Extensions
After hacking the source code to see the full command, I was able to work with it a bit.  In my own testing, I came up with this for my own specific needs:
dir | % { Rename-Item $_.FullName ([System.IO.Path]::GetFileNameWithoutExtension($_.fullname) + ".tif")}
By using the [System.IO.Path]::GetFileNameWithoutExtension() method you can simply chop off the extension and add whatever you like.

To suggest another direction this could go: if you wanted to get more elaborate with this, you could add a switch when you are expected specific files with varying extensions.  By doing so, you could process a directory once and modify the extensions at once.

2 comments:

  1. You don't have to resort to all that .NET code. Use built in PowerShell

    dir c:\work\*.abc | foreach {
    $new=Join-path -Path $_.Directory -ChildPath "$($_.basename).xyz"
    Rename-Item $_.FullName $new -PassThru
    }

    ReplyDelete
  2. I am learning. Thanks for the example. I have to overcome my C# mentality and use the tools the way they are built to be used. Will = old dog. Powershell = new tricks.

    ReplyDelete