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);
}
3
  • Never mind, I found a shorter solution: stackoverflow.com/a/1523078/1067499 Commented Jun 23, 2013 at 0:08
  • possible duplicate of How to loop through files and rename using PowerShell? Commented Jun 23, 2013 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++];...} Commented Jun 23, 2013 at 18:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.