none
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))
    }


    https://inframicrosoft.wordpress.com/

    • 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.

    https://inframicrosoft.wordpress.com/

    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.

    https://inframicrosoft.wordpress.com/

    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.

    https://inframicrosoft.wordpress.com/

    Friday, June 8, 2018 4:13 PM