Command/script to copy files with certain ext, which may have the same name, from folder structure to singe...











up vote
2
down vote

favorite












From a source directory structure (multiple folders), I need to copy all csv files to a single target directory. I found a command to do this, though files of the same name exist within different folders of the source structure, causing obvious issues when copied to one folder.



How can the files with duplicate names be renamed during the copy please (ideally: report.csv, reportcopy2.csv etc)? The job currently only copies a single instance of each file. Thanks for help.










share|improve this question




























    up vote
    2
    down vote

    favorite












    From a source directory structure (multiple folders), I need to copy all csv files to a single target directory. I found a command to do this, though files of the same name exist within different folders of the source structure, causing obvious issues when copied to one folder.



    How can the files with duplicate names be renamed during the copy please (ideally: report.csv, reportcopy2.csv etc)? The job currently only copies a single instance of each file. Thanks for help.










    share|improve this question


























      up vote
      2
      down vote

      favorite









      up vote
      2
      down vote

      favorite











      From a source directory structure (multiple folders), I need to copy all csv files to a single target directory. I found a command to do this, though files of the same name exist within different folders of the source structure, causing obvious issues when copied to one folder.



      How can the files with duplicate names be renamed during the copy please (ideally: report.csv, reportcopy2.csv etc)? The job currently only copies a single instance of each file. Thanks for help.










      share|improve this question















      From a source directory structure (multiple folders), I need to copy all csv files to a single target directory. I found a command to do this, though files of the same name exist within different folders of the source structure, causing obvious issues when copied to one folder.



      How can the files with duplicate names be renamed during the copy please (ideally: report.csv, reportcopy2.csv etc)? The job currently only copies a single instance of each file. Thanks for help.







      windows command-line






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 23 '15 at 13:40









      Der Hochstapler

      66.9k48230282




      66.9k48230282










      asked Aug 29 '12 at 10:13









      Nick

      1112




      1112






















          4 Answers
          4






          active

          oldest

          votes

















          up vote
          0
          down vote













          This is a slight work around - I know you wanted to name differently but I wondered if this will work for you.



          I would suggest you rename on copy to something like Foldername.Filename.csv.



          Use something like



          echo f | xcopy /f /y srcfile destfile


          EDIT



          I have tried for a few hours, I don't think what you want is possible with the CMD prompt or bat files.



          This is what I have



          set sDir=C:Documents and SettingsdrookDesktop
          set dDir="C:Documents and SettingsdrookDesktopFolder"

          cd C:Documents and SettingsdrookDesktop
          FOR /F %%a in ("*.txt") DO (
          xcopy "%%a" "C:Documents and SettingsdrookDesktopFolder"
          cd
          cd C:Documents and SettingsdrookDesktopFolder
          ren "%%a" "newName-%dir%.txt"
          cd
          cd C:Documents and SettingsdrookDesktop
          )

          pause


          It fails on the rename because it ignores the variable. So where I'm showing newName-%dir% (where dir is the variable) it would fail on newName-%%a as well...



          Sorry, I don't think it is possible.



          Having said that, this makes it look like it is possible: windows-batch-file-to-copy-and-keep-duplicates






          share|improve this answer























          • Thanks Dave. At the moment I am using FOR /R "src" %%a in ("*.csv") DO xcopy /d /y "%%a" "dest". Unsure how to integrate a name-change. Thanks
            – Nick
            Aug 29 '12 at 10:50










          • A bit more info - around 500 files from 3000 will be copied initially with perhaps groups of four or five with the same.
            – Nick
            Aug 29 '12 at 10:57


















          up vote
          0
          down vote













          This is similar to aflat's answer:



          setlocal enableDelayedExpansion
          set counter=1
          for /r src %%F in (*.csv) do (
          copy %%F dest%%~nF-!counter!%%~xF
          set /a counter=counter+1
          )





          share|improve this answer






























            up vote
            0
            down vote













            This should do it:



            @echo off
            setlocal
            set "sourcePath=c:source"
            set "targetPath=c:temptarget"
            set "pattern=*.csv"
            set prev=""
            set count=0

            for /f "tokens=1,2 delims=?" %%F in ('^(for /r "%sourcePath%" %%N in ^("%pattern%"^) do ^@echo %%~nxN?%%N?^)^|sort') do (
            call :copyFile "%%F" "%%G"
            set prev="%%F"
            )

            goto :eof

            :copyFile
            if /I %prev%==%1 (set /a count+=1) else (set count=0)
            if %count%==0 (set sufix=) else (set sufix=Copy%count%)
            echo copy "%~2" "%targetPath%%~n1%sufix%%~x1%"
            goto :eof


            What it does:




            • Lists all files matching pattern (most inner for) formatted as name?path

            • Sorts the list (by file name)

            • Parses sorted list line by line (outer for) and for each line (file)


              • if file name appears first time, copies it unmodified

              • if file name repeats, adds suffix and count_nr to a copy




            As it is now it will just echo copy command instead of executing it, so you can safely run it and check it's output. When you're ready, just remove echo from
            echo copy "%~2" "%targetPath%%~n1%sufix%%~x1%"






            share|improve this answer






























              up vote
              0
              down vote













              A simple PowerShell-Function can also do this:



              Function Start-FileCopyWDupliCheck(){
              # specify input-path, output-path, renaming-scheme, and file-extension here:
              param(
              [string]$path_in = 'D:Tempbla [ ] pfad[ ]',
              [string]$path_out = 'D:Tempmirrbla [123] 123',
              [string]$appendix = "_copy",
              [string]$fileext = "*.*"
              )

              # get all the files (and the necessary attributes)
              [array]$file_input = @(Get-ChildItem -LiteralPath $path_in -Filter $fileext -Recurse)
              [array]$file_input_path = @($file_input | ForEach-Object {$_.FullName})
              [array]$file_input_name = @($file_input | ForEach-Object {$_.BaseName})
              [array]$file_input_ext = @($file_input | ForEach-Object {$_.Extension})

              # check file-names for duplicates:
              for($i = 0; $i -lt $file_input_path.Length; $i++){
              $inter = "$path_out$($file_input_name[$i])$($file_input_ext[$i])" -replace '[[+]*?()\.]','$&'
              if((Test-Path -LiteralPath $inter) -eq $false){
              Write-Host "$inter not found in output-path -> leaving the name the same" -ForegroundColor Green
              $ready_for_copying = $inter
              }else{
              $j = 1
              Write-Host "$inter found in output-path -> appending `"$($appendix)XY`"..." -ForegroundColor Yellow
              while($true){
              $inter = "$path_out$($file_input_name[$i])$appendix$j$($file_input_ext[$i])" -replace '[[+]*?()\.]','$&'
              if((Test-Path -LiteralPath $inter) -eq $true){
              $j++
              continue
              }else{
              Write-Host "$appendix$j is working" -ForegroundColor Green
              $ready_for_copying = $inter
              break
              }
              }
              }
              # finally, copy the file:
              Copy-Item -LiteralPath $($file_input_path[$i]) -Destination $ready_for_copying
              }
              }

              Start-FileCopyWDupliCheck


              Of course one could remove the "write-host"-commands - they simply provide some visual feedback.
              Also, it would be possible to first gather the file-names and then later copy all files in a separate loop, possibly speeding things up.




              • simply make $ready_for_copying an array,

              • add (+=) the $inter-values to it,

              • add the check for already specified output-names in the if-conditions (e.g. $inter -in $ready_for_copying),

              • then move the copy-item-command to a new for-block (e.g. for($i = 0; $i -lt $ready_for_copying.Length; $i++)






              share|improve this answer





















                Your Answer








                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "3"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                 

                draft saved


                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f467755%2fcommand-script-to-copy-files-with-certain-ext-which-may-have-the-same-name-fro%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                0
                down vote













                This is a slight work around - I know you wanted to name differently but I wondered if this will work for you.



                I would suggest you rename on copy to something like Foldername.Filename.csv.



                Use something like



                echo f | xcopy /f /y srcfile destfile


                EDIT



                I have tried for a few hours, I don't think what you want is possible with the CMD prompt or bat files.



                This is what I have



                set sDir=C:Documents and SettingsdrookDesktop
                set dDir="C:Documents and SettingsdrookDesktopFolder"

                cd C:Documents and SettingsdrookDesktop
                FOR /F %%a in ("*.txt") DO (
                xcopy "%%a" "C:Documents and SettingsdrookDesktopFolder"
                cd
                cd C:Documents and SettingsdrookDesktopFolder
                ren "%%a" "newName-%dir%.txt"
                cd
                cd C:Documents and SettingsdrookDesktop
                )

                pause


                It fails on the rename because it ignores the variable. So where I'm showing newName-%dir% (where dir is the variable) it would fail on newName-%%a as well...



                Sorry, I don't think it is possible.



                Having said that, this makes it look like it is possible: windows-batch-file-to-copy-and-keep-duplicates






                share|improve this answer























                • Thanks Dave. At the moment I am using FOR /R "src" %%a in ("*.csv") DO xcopy /d /y "%%a" "dest". Unsure how to integrate a name-change. Thanks
                  – Nick
                  Aug 29 '12 at 10:50










                • A bit more info - around 500 files from 3000 will be copied initially with perhaps groups of four or five with the same.
                  – Nick
                  Aug 29 '12 at 10:57















                up vote
                0
                down vote













                This is a slight work around - I know you wanted to name differently but I wondered if this will work for you.



                I would suggest you rename on copy to something like Foldername.Filename.csv.



                Use something like



                echo f | xcopy /f /y srcfile destfile


                EDIT



                I have tried for a few hours, I don't think what you want is possible with the CMD prompt or bat files.



                This is what I have



                set sDir=C:Documents and SettingsdrookDesktop
                set dDir="C:Documents and SettingsdrookDesktopFolder"

                cd C:Documents and SettingsdrookDesktop
                FOR /F %%a in ("*.txt") DO (
                xcopy "%%a" "C:Documents and SettingsdrookDesktopFolder"
                cd
                cd C:Documents and SettingsdrookDesktopFolder
                ren "%%a" "newName-%dir%.txt"
                cd
                cd C:Documents and SettingsdrookDesktop
                )

                pause


                It fails on the rename because it ignores the variable. So where I'm showing newName-%dir% (where dir is the variable) it would fail on newName-%%a as well...



                Sorry, I don't think it is possible.



                Having said that, this makes it look like it is possible: windows-batch-file-to-copy-and-keep-duplicates






                share|improve this answer























                • Thanks Dave. At the moment I am using FOR /R "src" %%a in ("*.csv") DO xcopy /d /y "%%a" "dest". Unsure how to integrate a name-change. Thanks
                  – Nick
                  Aug 29 '12 at 10:50










                • A bit more info - around 500 files from 3000 will be copied initially with perhaps groups of four or five with the same.
                  – Nick
                  Aug 29 '12 at 10:57













                up vote
                0
                down vote










                up vote
                0
                down vote









                This is a slight work around - I know you wanted to name differently but I wondered if this will work for you.



                I would suggest you rename on copy to something like Foldername.Filename.csv.



                Use something like



                echo f | xcopy /f /y srcfile destfile


                EDIT



                I have tried for a few hours, I don't think what you want is possible with the CMD prompt or bat files.



                This is what I have



                set sDir=C:Documents and SettingsdrookDesktop
                set dDir="C:Documents and SettingsdrookDesktopFolder"

                cd C:Documents and SettingsdrookDesktop
                FOR /F %%a in ("*.txt") DO (
                xcopy "%%a" "C:Documents and SettingsdrookDesktopFolder"
                cd
                cd C:Documents and SettingsdrookDesktopFolder
                ren "%%a" "newName-%dir%.txt"
                cd
                cd C:Documents and SettingsdrookDesktop
                )

                pause


                It fails on the rename because it ignores the variable. So where I'm showing newName-%dir% (where dir is the variable) it would fail on newName-%%a as well...



                Sorry, I don't think it is possible.



                Having said that, this makes it look like it is possible: windows-batch-file-to-copy-and-keep-duplicates






                share|improve this answer














                This is a slight work around - I know you wanted to name differently but I wondered if this will work for you.



                I would suggest you rename on copy to something like Foldername.Filename.csv.



                Use something like



                echo f | xcopy /f /y srcfile destfile


                EDIT



                I have tried for a few hours, I don't think what you want is possible with the CMD prompt or bat files.



                This is what I have



                set sDir=C:Documents and SettingsdrookDesktop
                set dDir="C:Documents and SettingsdrookDesktopFolder"

                cd C:Documents and SettingsdrookDesktop
                FOR /F %%a in ("*.txt") DO (
                xcopy "%%a" "C:Documents and SettingsdrookDesktopFolder"
                cd
                cd C:Documents and SettingsdrookDesktopFolder
                ren "%%a" "newName-%dir%.txt"
                cd
                cd C:Documents and SettingsdrookDesktop
                )

                pause


                It fails on the rename because it ignores the variable. So where I'm showing newName-%dir% (where dir is the variable) it would fail on newName-%%a as well...



                Sorry, I don't think it is possible.



                Having said that, this makes it look like it is possible: windows-batch-file-to-copy-and-keep-duplicates







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited May 23 '17 at 12:41









                Community

                1




                1










                answered Aug 29 '12 at 10:34









                Dave

                23.2k74362




                23.2k74362












                • Thanks Dave. At the moment I am using FOR /R "src" %%a in ("*.csv") DO xcopy /d /y "%%a" "dest". Unsure how to integrate a name-change. Thanks
                  – Nick
                  Aug 29 '12 at 10:50










                • A bit more info - around 500 files from 3000 will be copied initially with perhaps groups of four or five with the same.
                  – Nick
                  Aug 29 '12 at 10:57


















                • Thanks Dave. At the moment I am using FOR /R "src" %%a in ("*.csv") DO xcopy /d /y "%%a" "dest". Unsure how to integrate a name-change. Thanks
                  – Nick
                  Aug 29 '12 at 10:50










                • A bit more info - around 500 files from 3000 will be copied initially with perhaps groups of four or five with the same.
                  – Nick
                  Aug 29 '12 at 10:57
















                Thanks Dave. At the moment I am using FOR /R "src" %%a in ("*.csv") DO xcopy /d /y "%%a" "dest". Unsure how to integrate a name-change. Thanks
                – Nick
                Aug 29 '12 at 10:50




                Thanks Dave. At the moment I am using FOR /R "src" %%a in ("*.csv") DO xcopy /d /y "%%a" "dest". Unsure how to integrate a name-change. Thanks
                – Nick
                Aug 29 '12 at 10:50












                A bit more info - around 500 files from 3000 will be copied initially with perhaps groups of four or five with the same.
                – Nick
                Aug 29 '12 at 10:57




                A bit more info - around 500 files from 3000 will be copied initially with perhaps groups of four or five with the same.
                – Nick
                Aug 29 '12 at 10:57












                up vote
                0
                down vote













                This is similar to aflat's answer:



                setlocal enableDelayedExpansion
                set counter=1
                for /r src %%F in (*.csv) do (
                copy %%F dest%%~nF-!counter!%%~xF
                set /a counter=counter+1
                )





                share|improve this answer



























                  up vote
                  0
                  down vote













                  This is similar to aflat's answer:



                  setlocal enableDelayedExpansion
                  set counter=1
                  for /r src %%F in (*.csv) do (
                  copy %%F dest%%~nF-!counter!%%~xF
                  set /a counter=counter+1
                  )





                  share|improve this answer

























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    This is similar to aflat's answer:



                    setlocal enableDelayedExpansion
                    set counter=1
                    for /r src %%F in (*.csv) do (
                    copy %%F dest%%~nF-!counter!%%~xF
                    set /a counter=counter+1
                    )





                    share|improve this answer














                    This is similar to aflat's answer:



                    setlocal enableDelayedExpansion
                    set counter=1
                    for /r src %%F in (*.csv) do (
                    copy %%F dest%%~nF-!counter!%%~xF
                    set /a counter=counter+1
                    )






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited May 23 '17 at 12:41









                    Community

                    1




                    1










                    answered Aug 29 '12 at 19:45









                    Scott

                    15.4k113789




                    15.4k113789






















                        up vote
                        0
                        down vote













                        This should do it:



                        @echo off
                        setlocal
                        set "sourcePath=c:source"
                        set "targetPath=c:temptarget"
                        set "pattern=*.csv"
                        set prev=""
                        set count=0

                        for /f "tokens=1,2 delims=?" %%F in ('^(for /r "%sourcePath%" %%N in ^("%pattern%"^) do ^@echo %%~nxN?%%N?^)^|sort') do (
                        call :copyFile "%%F" "%%G"
                        set prev="%%F"
                        )

                        goto :eof

                        :copyFile
                        if /I %prev%==%1 (set /a count+=1) else (set count=0)
                        if %count%==0 (set sufix=) else (set sufix=Copy%count%)
                        echo copy "%~2" "%targetPath%%~n1%sufix%%~x1%"
                        goto :eof


                        What it does:




                        • Lists all files matching pattern (most inner for) formatted as name?path

                        • Sorts the list (by file name)

                        • Parses sorted list line by line (outer for) and for each line (file)


                          • if file name appears first time, copies it unmodified

                          • if file name repeats, adds suffix and count_nr to a copy




                        As it is now it will just echo copy command instead of executing it, so you can safely run it and check it's output. When you're ready, just remove echo from
                        echo copy "%~2" "%targetPath%%~n1%sufix%%~x1%"






                        share|improve this answer



























                          up vote
                          0
                          down vote













                          This should do it:



                          @echo off
                          setlocal
                          set "sourcePath=c:source"
                          set "targetPath=c:temptarget"
                          set "pattern=*.csv"
                          set prev=""
                          set count=0

                          for /f "tokens=1,2 delims=?" %%F in ('^(for /r "%sourcePath%" %%N in ^("%pattern%"^) do ^@echo %%~nxN?%%N?^)^|sort') do (
                          call :copyFile "%%F" "%%G"
                          set prev="%%F"
                          )

                          goto :eof

                          :copyFile
                          if /I %prev%==%1 (set /a count+=1) else (set count=0)
                          if %count%==0 (set sufix=) else (set sufix=Copy%count%)
                          echo copy "%~2" "%targetPath%%~n1%sufix%%~x1%"
                          goto :eof


                          What it does:




                          • Lists all files matching pattern (most inner for) formatted as name?path

                          • Sorts the list (by file name)

                          • Parses sorted list line by line (outer for) and for each line (file)


                            • if file name appears first time, copies it unmodified

                            • if file name repeats, adds suffix and count_nr to a copy




                          As it is now it will just echo copy command instead of executing it, so you can safely run it and check it's output. When you're ready, just remove echo from
                          echo copy "%~2" "%targetPath%%~n1%sufix%%~x1%"






                          share|improve this answer

























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            This should do it:



                            @echo off
                            setlocal
                            set "sourcePath=c:source"
                            set "targetPath=c:temptarget"
                            set "pattern=*.csv"
                            set prev=""
                            set count=0

                            for /f "tokens=1,2 delims=?" %%F in ('^(for /r "%sourcePath%" %%N in ^("%pattern%"^) do ^@echo %%~nxN?%%N?^)^|sort') do (
                            call :copyFile "%%F" "%%G"
                            set prev="%%F"
                            )

                            goto :eof

                            :copyFile
                            if /I %prev%==%1 (set /a count+=1) else (set count=0)
                            if %count%==0 (set sufix=) else (set sufix=Copy%count%)
                            echo copy "%~2" "%targetPath%%~n1%sufix%%~x1%"
                            goto :eof


                            What it does:




                            • Lists all files matching pattern (most inner for) formatted as name?path

                            • Sorts the list (by file name)

                            • Parses sorted list line by line (outer for) and for each line (file)


                              • if file name appears first time, copies it unmodified

                              • if file name repeats, adds suffix and count_nr to a copy




                            As it is now it will just echo copy command instead of executing it, so you can safely run it and check it's output. When you're ready, just remove echo from
                            echo copy "%~2" "%targetPath%%~n1%sufix%%~x1%"






                            share|improve this answer














                            This should do it:



                            @echo off
                            setlocal
                            set "sourcePath=c:source"
                            set "targetPath=c:temptarget"
                            set "pattern=*.csv"
                            set prev=""
                            set count=0

                            for /f "tokens=1,2 delims=?" %%F in ('^(for /r "%sourcePath%" %%N in ^("%pattern%"^) do ^@echo %%~nxN?%%N?^)^|sort') do (
                            call :copyFile "%%F" "%%G"
                            set prev="%%F"
                            )

                            goto :eof

                            :copyFile
                            if /I %prev%==%1 (set /a count+=1) else (set count=0)
                            if %count%==0 (set sufix=) else (set sufix=Copy%count%)
                            echo copy "%~2" "%targetPath%%~n1%sufix%%~x1%"
                            goto :eof


                            What it does:




                            • Lists all files matching pattern (most inner for) formatted as name?path

                            • Sorts the list (by file name)

                            • Parses sorted list line by line (outer for) and for each line (file)


                              • if file name appears first time, copies it unmodified

                              • if file name repeats, adds suffix and count_nr to a copy




                            As it is now it will just echo copy command instead of executing it, so you can safely run it and check it's output. When you're ready, just remove echo from
                            echo copy "%~2" "%targetPath%%~n1%sufix%%~x1%"







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Aug 30 '12 at 11:35

























                            answered Aug 29 '12 at 23:53









                            wmz

                            5,62211127




                            5,62211127






















                                up vote
                                0
                                down vote













                                A simple PowerShell-Function can also do this:



                                Function Start-FileCopyWDupliCheck(){
                                # specify input-path, output-path, renaming-scheme, and file-extension here:
                                param(
                                [string]$path_in = 'D:Tempbla [ ] pfad[ ]',
                                [string]$path_out = 'D:Tempmirrbla [123] 123',
                                [string]$appendix = "_copy",
                                [string]$fileext = "*.*"
                                )

                                # get all the files (and the necessary attributes)
                                [array]$file_input = @(Get-ChildItem -LiteralPath $path_in -Filter $fileext -Recurse)
                                [array]$file_input_path = @($file_input | ForEach-Object {$_.FullName})
                                [array]$file_input_name = @($file_input | ForEach-Object {$_.BaseName})
                                [array]$file_input_ext = @($file_input | ForEach-Object {$_.Extension})

                                # check file-names for duplicates:
                                for($i = 0; $i -lt $file_input_path.Length; $i++){
                                $inter = "$path_out$($file_input_name[$i])$($file_input_ext[$i])" -replace '[[+]*?()\.]','$&'
                                if((Test-Path -LiteralPath $inter) -eq $false){
                                Write-Host "$inter not found in output-path -> leaving the name the same" -ForegroundColor Green
                                $ready_for_copying = $inter
                                }else{
                                $j = 1
                                Write-Host "$inter found in output-path -> appending `"$($appendix)XY`"..." -ForegroundColor Yellow
                                while($true){
                                $inter = "$path_out$($file_input_name[$i])$appendix$j$($file_input_ext[$i])" -replace '[[+]*?()\.]','$&'
                                if((Test-Path -LiteralPath $inter) -eq $true){
                                $j++
                                continue
                                }else{
                                Write-Host "$appendix$j is working" -ForegroundColor Green
                                $ready_for_copying = $inter
                                break
                                }
                                }
                                }
                                # finally, copy the file:
                                Copy-Item -LiteralPath $($file_input_path[$i]) -Destination $ready_for_copying
                                }
                                }

                                Start-FileCopyWDupliCheck


                                Of course one could remove the "write-host"-commands - they simply provide some visual feedback.
                                Also, it would be possible to first gather the file-names and then later copy all files in a separate loop, possibly speeding things up.




                                • simply make $ready_for_copying an array,

                                • add (+=) the $inter-values to it,

                                • add the check for already specified output-names in the if-conditions (e.g. $inter -in $ready_for_copying),

                                • then move the copy-item-command to a new for-block (e.g. for($i = 0; $i -lt $ready_for_copying.Length; $i++)






                                share|improve this answer

























                                  up vote
                                  0
                                  down vote













                                  A simple PowerShell-Function can also do this:



                                  Function Start-FileCopyWDupliCheck(){
                                  # specify input-path, output-path, renaming-scheme, and file-extension here:
                                  param(
                                  [string]$path_in = 'D:Tempbla [ ] pfad[ ]',
                                  [string]$path_out = 'D:Tempmirrbla [123] 123',
                                  [string]$appendix = "_copy",
                                  [string]$fileext = "*.*"
                                  )

                                  # get all the files (and the necessary attributes)
                                  [array]$file_input = @(Get-ChildItem -LiteralPath $path_in -Filter $fileext -Recurse)
                                  [array]$file_input_path = @($file_input | ForEach-Object {$_.FullName})
                                  [array]$file_input_name = @($file_input | ForEach-Object {$_.BaseName})
                                  [array]$file_input_ext = @($file_input | ForEach-Object {$_.Extension})

                                  # check file-names for duplicates:
                                  for($i = 0; $i -lt $file_input_path.Length; $i++){
                                  $inter = "$path_out$($file_input_name[$i])$($file_input_ext[$i])" -replace '[[+]*?()\.]','$&'
                                  if((Test-Path -LiteralPath $inter) -eq $false){
                                  Write-Host "$inter not found in output-path -> leaving the name the same" -ForegroundColor Green
                                  $ready_for_copying = $inter
                                  }else{
                                  $j = 1
                                  Write-Host "$inter found in output-path -> appending `"$($appendix)XY`"..." -ForegroundColor Yellow
                                  while($true){
                                  $inter = "$path_out$($file_input_name[$i])$appendix$j$($file_input_ext[$i])" -replace '[[+]*?()\.]','$&'
                                  if((Test-Path -LiteralPath $inter) -eq $true){
                                  $j++
                                  continue
                                  }else{
                                  Write-Host "$appendix$j is working" -ForegroundColor Green
                                  $ready_for_copying = $inter
                                  break
                                  }
                                  }
                                  }
                                  # finally, copy the file:
                                  Copy-Item -LiteralPath $($file_input_path[$i]) -Destination $ready_for_copying
                                  }
                                  }

                                  Start-FileCopyWDupliCheck


                                  Of course one could remove the "write-host"-commands - they simply provide some visual feedback.
                                  Also, it would be possible to first gather the file-names and then later copy all files in a separate loop, possibly speeding things up.




                                  • simply make $ready_for_copying an array,

                                  • add (+=) the $inter-values to it,

                                  • add the check for already specified output-names in the if-conditions (e.g. $inter -in $ready_for_copying),

                                  • then move the copy-item-command to a new for-block (e.g. for($i = 0; $i -lt $ready_for_copying.Length; $i++)






                                  share|improve this answer























                                    up vote
                                    0
                                    down vote










                                    up vote
                                    0
                                    down vote









                                    A simple PowerShell-Function can also do this:



                                    Function Start-FileCopyWDupliCheck(){
                                    # specify input-path, output-path, renaming-scheme, and file-extension here:
                                    param(
                                    [string]$path_in = 'D:Tempbla [ ] pfad[ ]',
                                    [string]$path_out = 'D:Tempmirrbla [123] 123',
                                    [string]$appendix = "_copy",
                                    [string]$fileext = "*.*"
                                    )

                                    # get all the files (and the necessary attributes)
                                    [array]$file_input = @(Get-ChildItem -LiteralPath $path_in -Filter $fileext -Recurse)
                                    [array]$file_input_path = @($file_input | ForEach-Object {$_.FullName})
                                    [array]$file_input_name = @($file_input | ForEach-Object {$_.BaseName})
                                    [array]$file_input_ext = @($file_input | ForEach-Object {$_.Extension})

                                    # check file-names for duplicates:
                                    for($i = 0; $i -lt $file_input_path.Length; $i++){
                                    $inter = "$path_out$($file_input_name[$i])$($file_input_ext[$i])" -replace '[[+]*?()\.]','$&'
                                    if((Test-Path -LiteralPath $inter) -eq $false){
                                    Write-Host "$inter not found in output-path -> leaving the name the same" -ForegroundColor Green
                                    $ready_for_copying = $inter
                                    }else{
                                    $j = 1
                                    Write-Host "$inter found in output-path -> appending `"$($appendix)XY`"..." -ForegroundColor Yellow
                                    while($true){
                                    $inter = "$path_out$($file_input_name[$i])$appendix$j$($file_input_ext[$i])" -replace '[[+]*?()\.]','$&'
                                    if((Test-Path -LiteralPath $inter) -eq $true){
                                    $j++
                                    continue
                                    }else{
                                    Write-Host "$appendix$j is working" -ForegroundColor Green
                                    $ready_for_copying = $inter
                                    break
                                    }
                                    }
                                    }
                                    # finally, copy the file:
                                    Copy-Item -LiteralPath $($file_input_path[$i]) -Destination $ready_for_copying
                                    }
                                    }

                                    Start-FileCopyWDupliCheck


                                    Of course one could remove the "write-host"-commands - they simply provide some visual feedback.
                                    Also, it would be possible to first gather the file-names and then later copy all files in a separate loop, possibly speeding things up.




                                    • simply make $ready_for_copying an array,

                                    • add (+=) the $inter-values to it,

                                    • add the check for already specified output-names in the if-conditions (e.g. $inter -in $ready_for_copying),

                                    • then move the copy-item-command to a new for-block (e.g. for($i = 0; $i -lt $ready_for_copying.Length; $i++)






                                    share|improve this answer












                                    A simple PowerShell-Function can also do this:



                                    Function Start-FileCopyWDupliCheck(){
                                    # specify input-path, output-path, renaming-scheme, and file-extension here:
                                    param(
                                    [string]$path_in = 'D:Tempbla [ ] pfad[ ]',
                                    [string]$path_out = 'D:Tempmirrbla [123] 123',
                                    [string]$appendix = "_copy",
                                    [string]$fileext = "*.*"
                                    )

                                    # get all the files (and the necessary attributes)
                                    [array]$file_input = @(Get-ChildItem -LiteralPath $path_in -Filter $fileext -Recurse)
                                    [array]$file_input_path = @($file_input | ForEach-Object {$_.FullName})
                                    [array]$file_input_name = @($file_input | ForEach-Object {$_.BaseName})
                                    [array]$file_input_ext = @($file_input | ForEach-Object {$_.Extension})

                                    # check file-names for duplicates:
                                    for($i = 0; $i -lt $file_input_path.Length; $i++){
                                    $inter = "$path_out$($file_input_name[$i])$($file_input_ext[$i])" -replace '[[+]*?()\.]','$&'
                                    if((Test-Path -LiteralPath $inter) -eq $false){
                                    Write-Host "$inter not found in output-path -> leaving the name the same" -ForegroundColor Green
                                    $ready_for_copying = $inter
                                    }else{
                                    $j = 1
                                    Write-Host "$inter found in output-path -> appending `"$($appendix)XY`"..." -ForegroundColor Yellow
                                    while($true){
                                    $inter = "$path_out$($file_input_name[$i])$appendix$j$($file_input_ext[$i])" -replace '[[+]*?()\.]','$&'
                                    if((Test-Path -LiteralPath $inter) -eq $true){
                                    $j++
                                    continue
                                    }else{
                                    Write-Host "$appendix$j is working" -ForegroundColor Green
                                    $ready_for_copying = $inter
                                    break
                                    }
                                    }
                                    }
                                    # finally, copy the file:
                                    Copy-Item -LiteralPath $($file_input_path[$i]) -Destination $ready_for_copying
                                    }
                                    }

                                    Start-FileCopyWDupliCheck


                                    Of course one could remove the "write-host"-commands - they simply provide some visual feedback.
                                    Also, it would be possible to first gather the file-names and then later copy all files in a separate loop, possibly speeding things up.




                                    • simply make $ready_for_copying an array,

                                    • add (+=) the $inter-values to it,

                                    • add the check for already specified output-names in the if-conditions (e.g. $inter -in $ready_for_copying),

                                    • then move the copy-item-command to a new for-block (e.g. for($i = 0; $i -lt $ready_for_copying.Length; $i++)







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Jun 18 '17 at 16:43









                                    flolilolilo

                                    1,4281520




                                    1,4281520






























                                         

                                        draft saved


                                        draft discarded



















































                                         


                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f467755%2fcommand-script-to-copy-files-with-certain-ext-which-may-have-the-same-name-fro%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Список кардиналов, возведённых папой римским Каликстом III

                                        Deduzione

                                        Mysql.sock missing - “Can't connect to local MySQL server through socket”