Archive

Archive for November, 2009

PowerShell: Rename files to include parent directory name

November 18th, 2009 Fishbowler 1 comment

This took me longer than it should have to figure out.
Since I couldn’t find exactly what I was looking for on Google, I’ll share it with everyone in case they need the same thing someday.

This script renames all log files within a directory to include the parent directory name.
If your files are in a folder named “WebLogs” and your logs are named “File1.log” and “File2.log”, you’ll end up with “WebLogs-File1.log” and “WebLogs-File2.log”.

I needed this to analyse a log of IIS logs from a bunch of different places. For those not familiar, all IIS Extended logs are named exYYMMDD (where YYMMDD are date tokens).

The PowerShell I used:

Param($path)

$files = @(dir *.log -Path $path -recurse)

foreach($file in $files) {
	Rename-Item ($file.Directory.ToString() + '\' + $file.Name) ($file.Directory.Name + '-' + $file.Name)
}

The Usage:

  • Save as RenameToParent.ps1
  • Run:
.\RenameToParent.ps1 -path F:\Logs

Hope this helps someone…

Categories: My Software, Uncategorized Tags: