Renaming Files

Let’s have a little fun with Rename-Item:

[3112:0]PS> dir


    Directory: Microsoft.PowerShell.Core\FileSystem::C:\temp\jps


Mode                LastWriteTime     Length Name
—-                ————-     —— —-
-a—          3/5/2007   4:21 PM        948 a
-a—          3/5/2007   4:21 PM       1214 b
-a—          3/5/2007   4:21 PM       1480 c


[3112:0]PS> dir |Rename-Item -NewName {$_.Name + “1”}
[3112:0]PS> dir


    Directory: Microsoft.PowerShell.Core\FileSystem::C:\temp\jps


Mode                LastWriteTime     Length Name
—-                ————-     —— —-
-a—          3/5/2007   4:21 PM        948 a1
-a—          3/5/2007   4:21 PM       1214 b1
-a—          3/5/2007   4:21 PM       1480 c1

[3112:0]PS> foreach ($f in dir) {Rename-Item $f -NewName ($f.Name + “2”)}
[3112:0]PS> dir


    Directory: Microsoft.PowerShell.Core\FileSystem::C:\temp\jps


Mode                LastWriteTime     Length Name
—-                ————-     —— —-
-a—          3/5/2007   4:21 PM        948 a12
-a—          3/5/2007   4:21 PM       1214 b12
-a—          3/5/2007   4:21 PM       1480 c12

[3112:0]PS> dir |%{Rename-Item $_ $($_.Name +”3″)}
[3112:0]PS> dir


    Directory: Microsoft.PowerShell.Core\FileSystem::C:\temp\jps


Mode                LastWriteTime     Length Name
—-                ————-     —— —-
-a—          3/5/2007   4:21 PM        948 a123
-a—          3/5/2007   4:21 PM       1214 b123
-a—          3/5/2007   4:21 PM       1480 c123

[3112:0]PS> dir | %{$x=0} {Rename-Item $_ -NewName “Base$x”; $x++ }
[3112:0]PS> dir


    Directory: Microsoft.PowerShell.Core\FileSystem::C:\temp\jps


Mode                LastWriteTime     Length Name
—-                ————-     —— —-
-a—          3/5/2007   8:24 PM       1086 Base0
-a—          3/5/2007   8:24 PM       1398 Base1
-a—          3/5/2007   8:24 PM       1710 Base2



Enjoy!

Jeffrey Snover [MSFT]
Windows PowerShell/MMC Architect
Visit the Windows PowerShell Team blog at: http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at: http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx