2

I tried using the following code to rename a folder of files "C:\www\folderx" using a text list "..\list.txt", but I can't figure out how to get the current file index:

Get-Childitem C:\www\folderx | % {
    $OldName = $_.name;
    $NewName = (GC ..\list.txt)[<CURRENT INDEX SHOULD GO HERE>];
    # Rename-Item -Newname $NewName;
    Write-Output $("Renamed {0} to {1}" -f $OldName,$NewName);
}
gatzkerob
  • 877
  • 2
  • 12
  • 32
  • Never mind, I found a shorter solution: http://stackoverflow.com/a/1523078/1067499 – gatzkerob Jun 23 '13 at 00:08
  • possible duplicate of [How to loop through files and rename using PowerShell?](http://stackoverflow.com/questions/1523043/how-to-loop-through-files-and-rename-using-powershell) – Ansgar Wiechers Jun 23 '13 at 10:17
  • 3
    For efficiency, don't put the `(GC ..\list.txt)` inside the foreach. You're re-reading the contents of list.txt for every file passed down the pipeline. You could put that in the begin block e.g. `... | Foreach -Begin {$i=0;$c = gc ..\list.txt} {$newname = $c[$i++];...}` – Keith Hill Jun 23 '13 at 18:35

0 Answers0