Script optimization - Powershell RRS feed

  • General discussion

  • Hello everyone

    What would be the most elegant or short alternative to the code below?

    $content = Get-Content C:\temp\names.txt
    $files = Get-ChildItem -File C:\files\
    foreach ($file in $files) {
        Rename-Item -Path $file.FullName -NewName $content.Item($files.IndexOf($file))

    • Changed type Bill_Stewart Monday, July 30, 2018 1:42 PM
    • Moved by Bill_Stewart Monday, July 30, 2018 1:42 PM Unanswerable drive-by question
    Friday, June 8, 2018 2:29 PM

All replies

  • Why? Is the code not working?

    -- Bill Stewart [Bill_Stewart]

    Friday, June 8, 2018 2:49 PM
  • Thanks for responding, Bill.

    It works. I was just wondering if there is any more direct way to do the same task. I am studying and would like to improve my knowledge.

    Friday, June 8, 2018 2:59 PM
  • The following would be faster if there  are more than a few files.

    $content = Get-Content C:\temp\names.txt
    Get-ChildItem C:\files -File |
        ForEach-Object{ $_| Rename-Item -NewName $content.Item($files.IndexOf($file)) }


    Friday, June 8, 2018 3:27 PM
  • Actually your code will not work as it doesn't make any sense.  Perhaps you need to rethink what you are  trying to do.


    Friday, June 8, 2018 3:35 PM
  • Thanks for the answer

    Particularly for me, it works.
    I rename the files with the names contained, one in each line, in the txt.

    Friday, June 8, 2018 3:59 PM
  • There is no way to correctly match the names in your code.  There is no match between the names in the file  to  correctly match  the names in the list and when they match the  rename will just be back to the same name.

    You need to think about and test this more.


    Friday, June 8, 2018 4:04 PM
  • Ok. Thank You, Jrv.

    Friday, June 8, 2018 4:13 PM