Renaming files using Powershell

Recently, I unpacked somebody’s installer.

I know, it might be borderline with the license, but I just wanted to take a peek.

It’s a redistributable package which is distributed with a development environment so it can be incorporated into an installer bootstrapper. And it has been updated several times for individual download as an update or full install, yet without packaging information for said bootstrapper package.

If that doesn’t call for some peeking and tweaking, I don’t know what does.

When I unpacked and "darked" the installer, I was left with a bunch of files named with arbitrary numbers in arbitrary directories and an XML document that had the information about those names in various elements across it’s hierarchy.

CMD.EXE’s "FOR /F" is a blessing, but in it’s heyday, nobody thought of renaming files based on information in XML documents.

Short of creating an XSLT, I gave Powershell a try.

But it doesn’t do it in a one-liner, due to the pain in the neck that is XPath’s handling of default XML Namespaces:

[xml]$wxs = get-content D:TempReportViewerReportViewer.wxs

$nsmgr = new-object System.Xml.XmlNamespaceManager($wxs.get_NameTable())


$wxs.SelectNodes("//w:File",$nsmgr) | ForEach-Object -process {$f = get-childitem -path $_.Source;$f.MoveTo($f.DirectoryName + ” + $_.LongName)}

The foreach-object is an ugly workaround. A colleague of mine (who I tortured with every step to get to these lines) brought up the idea of taking the object pipeline concept a little further by using

Add-Member -memberType NoteProperty -passThru

to join the two streams of information.

A lot of stuff to rename four files.

Completion of the latter approach left as homework for the interested reader.


Please note: script code fragment samples provided "AS IS", without support or warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and non-infringement. In no event shall the author or copyright holder be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.

This entry was posted in Coding Horror. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s