none
foreach loop RRS feed

  • Question

  • Hi

    Am trying to rename my files in such a way that all the files in $filenames are renamed with names in $lastname and $firstname variables.

    to achieve this am using for ForEach loop in here , but the output isn't turning out in the way i wanted it to be,, the output is repeating multiple times and changing the sequence of how the filenames should be replaced.

    please let me know in which way am using foreach loop wrongly.

    Script:-

    $filenames=Get-ChildItem -Path .\rename | select Name
    $filenamess=$filenames.name
    $lastnames=Get-Content -Path .\LastName.txt
    $firstnames=Get-Content -Path .\FirstName.txt

    ForEach($filename in $filenamess)
    {
        ForEach($lastname in $lastnames)
            {
              ForEach($firstname in $firstnames)
            {
        Rename-Item -Path C:\Users\VY073660\Downloads\New_folder\rename\$filename -NewName $lastname+$firstname.txt -Verbose
        }
       
       }
      }
      

    Tuesday, February 11, 2020 6:56 PM

All replies

  • First of all - please format your code as code: How to Use the Code Feature in a TechNet Forum Post.

    Then you'd need to "synchronize" your file names with your LastNames with your FirstNames. So they need to have the same amount of elements. If not you will have to explain how you like to deal with that precondition.

    At the moment your inner most loop runs with all its elements for each single elements of your last names and this both runs again for all elements of your file names. To make this more visible you could simple output all elements in your inner most loop.  ;-)


    Live long and prosper!

    (79,108,97,102|%{[char]$_})-join''

    • Edited by BOfH-666 Tuesday, February 11, 2020 11:29 PM
    Tuesday, February 11, 2020 9:55 PM
  • There is likely no way to synchronize this.  Why are the names in two files?  How do you know which files get which names?

    Lack of planning and lack of understanding of data and programming are the cause of this.

    Step back and rethink what you are trying to do.  YOU will need to figure out how to combine your files or set some specific rules of how these things are to be matched.


    \_(ツ)_/

    Tuesday, February 11, 2020 11:24 PM