• Batch File: search list of names, copy any file containing one of those names?

    Home » Forums » AskWoody support » Windows » Windows – other » Batch File: search list of names, copy any file containing one of those names?

    Author
    Topic
    #503120

    SO I’ve got a directory with a long list of files, each with a naming structure that relates to what’s inside the file. I need to find and pull a specific file, copying it to a transfer folder, so I can work on it, while preserving the original file. This is all fine when I have a small number of files to search for, but is there a way to do this with a list of 100’s of files?

    I’m thinking have the list of search names saved as a .txt or .csv file on the transfer folder, then run a batch script that searches through and searches the data file directory and when it finds a match, copies the data file, and moves on, until the end.

    Any help?

    REM @ECHO OFF

    :creates backup folder
    IF NOT EXIST C:TRANSFERSEARCH_RESULTS MD C:TRANSFERBACKUP_LOTS

    :grabs the date and time and makes a folder name
    for /f “tokens=2-8 delims=:-. ” %%A in (‘NOW’) do set BACKUPDIR=%%A%%B%%C-%%D%%E

    :Makes the timestamped directory.
    MD C:TRANSFERBACKUP_LOTS%BACKUPDIR%

    REM SETLOCAL

    :defines variable name
    SET LOCAL_LOTS=C:TRANSFERBACKUP_LOTS%BACKUPDIR%

    :search name list
    _____?

    :copies from the data folder to the timestamped transfer folder
    COPY C:DATA_FOLDER*.DAT %LOCAL_RECIPES%

    :repeat until end of name list
    _______?

    REM PAUSE

    Viewing 25 reply threads
    Author
    Replies
    • #1537119

      wierd, it looks like my OP disappeared.

      REM @ECHO OFF

      :creates backup folder
      IF NOT EXIST C:TRANSFERBACKUP_LOTS MD C:TRANSFERBACKUP_LOTS

      :grabs the date and time and makes a folder name
      for /f “tokens=2-8 delims=:-. ” %%A in (‘NOW’) do set BACKUPDIR=%%A%%B%%C-%%D%%E

      :Makes the timestamped directory.
      MD C:TRANSFERBACKUP_LOTS%BACKUPDIR%

      REM SETLOCAL

      :defines variable name
      SET LOCAL_LOTS=C:TRANSFERBACKUP_LOTS%BACKUPDIR%

      :search name list
      _____?

      :copies from the data folder to the timestamped transfer folder
      COPY C:DATA_FOLDER*.DAT %LOCAL_RECIPES%

      :repeat until end of name list
      _______?

      REM PAUSE

    • #1537146

      Nothing showing here to read.

      Before you wonder "Am I doing things right," ask "Am I doing the right things?"
    • #1537148

      Auto moderated – try reading it now.

    • #1537186

      What’s wrong with using the search in Windows Explorer and then copying the file?

      cheers, Paul

      • #1537230

        What’s wrong with using the search in Windows Explorer and then copying the file?
        cheers, Paul

        why do things manually when you can automate it? Doing one search at a time for 100+ files? really?

        • #1537246

          why do things manually when you can automate it?

          Didn’t realize you wanted to move 100s – not reading properly, again. 🙂

          cheers, Paul

          • #1537247

            Didn’t realize you wanted to move 100s – not reading properly, again. 🙂

            cheers, Paul

            🙂 ha, no worries. I think it just sucks to do things manually. I’m a chemical engineer, never really studied coding, and there’s so much that I see in my daily job that could be solved with just a little bit of coding, but I’m kinda clueless. I know general Boolean logic, but not the specifics. I wish companies would have roaming teams of coders to solve little problems like this. I feel like a coding person would be able to create a solution a hell of a lot quicker than I can.

    • #1537220

      Please tell me if I’ve understood this correctly.

        [*]You have a folder with lots of .DAT files in it.
        [*]You have a list of some of the .DAT files in that folder that you wish to copy to a separate backup folder, whose name includes the date and time (in some format which you haven’t specified clearly).

      It would be a good idea if you could give examples of the folder names and file names which you wish to copy. I DO hope that the filenames contain only alphameric characters.

      Given good will on the part of the filenames, this is a fairly simple task, which I will begin when you can give me the requested example names!

      BTW – where did %local_recipes% come from?!

      BATcher

      Plethora means a lot to me.

      • #1537233

        Please tell me if I’ve understood this correctly.

          [*]You have a folder with lots of .DAT files in it.
          [*]You have a list of some of the .DAT files in that folder that you wish to copy to a separate backup folder, whose name includes the date and time (in some format which you haven’t specified clearly).

        It would be a good idea if you could give examples of the folder names and file names which you wish to copy. I DO hope that the filenames contain only alphameric characters.

        Given good will on the part of the filenames, this is a fairly simple task, which I will begin when you can give me the requested example names!

        BTW – where did %local_recipes% come from?!

        yes, very close. I’ve got a directory folder on a network drive that saves a bunch of .DAT files using “LOT_TYPE_PRODUCT.dat”
        “C:DATA_FOLDERLOT_TYPE_PRODUCT.DAT” (example “Lot1_Type1_Product1.dat”, “Lot2_Type1_Product1.dat”, “Lotn+1_Typen+1_Productn+1.dat”)

        I have a list of “LOTs” that I need to retrieve the .dat files for. I can save this list in any way necessary (excel, .txt, .csv, whatever). (ex: Lot1, Lot2, Lot6, Lot7, Lot818, etc)

        I want to run some sort of script or code that will search the given list, then grab and copy all of those .dat files containing that “LOT” name over to a transfer folder for easy access.

        *extra credit* I want to be able to run this script inside the network space, remote desktop, and have it search through half a dozen IP-addresses, network drives, each with their own “DATA_FOLDER”, crawling through and grabbing a matching .dat file from the list, rather than go to each network drive one at a time.

    • #1537231

      Here’s my first draft, in my style of BATch file writing!
      It makes assumptions…
      No testing has yet been done…

      Code:
      @echo off
      
      :: Copy all the .dat files whose names appear in the text file  filelist.txt
      ::    (which is assumed to be in the source folder)   
      ::  from the source folder  c:datafolder
      ::  to   the target folder  c:transferbackup_lotsyyyymmdd-hhmm
      
      :: filelist.txt entries are expected to look rather like:
      ::   file1.dat
      ::   file number two.dat
      ::   file_3.dat
      ::   file number-4.dat
      ::     ... and so on
      
      :: obtain the current date and time regardless of locale/region/country
      ::   %yy% will contain four digits, 20nn;
      ::   %mm%, %dd% and time variables %hr%, %mn%, %sc% and %th% contain two digits
      if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
      for /f "skip=1 tokens=2-4 delims=(-)" %%a in ('echo.^|date') do (
         for /f "tokens=%toks% delims=.-/ " %%e in ('date /t')     do (
            for /f "tokens=5-8 delims=:., " %%i in ('echo.^|time') do (
              (set %%a=%%e) & (set %%b=%%f) & (set %%c=%%g) & rem create yy, mm, dd
              (set hr=%%i)  & (set mn=%%j)  & (set sc=%%k)  & (set th=%%l)
              rem  note the variable names for Time: hr, mn, sc, th
      )))
      if 1%hr% LSS 20  (set hr=0%hr%)  & :: ensure 2-digit hours in %hr%
      
      :: create the full target directory path 
      ::   with the final directory name in the form  yyyymmdd-hrmn  (eg 20151114-1523)
      set target=c:transferbackup_lots%yy%%mm%%dd%-%hr%%mn%
      
      :: create the full target directory path, ignoring any error message
      md %target% 2>nul
      
      :: set up the full source path
      set source=c:data_folder
      
      :: the clever bit: read filelist.txt and, for each filename, 
      ::   copy it from the source path to the target path
      ::   it's easier to do the processing in a subroutine
      
      for /f "tokens=*" %%a in (filelist.txt) do call :process "%%a"
      
      :: that's it, folks!  (maybe a directory ist would be useful...)
      
      pause
      
      endlocal
      
      exit /b 0
      
      ::-----------------------------------------------------------------------------
      :process  the file name in double-quotes passed to this subroutine
      
      :; remove the initial and final double-quotes
      set fn=%~1
      
      :: test that the file extension is .dat
      if /i not "%~x0"==".dat" (
        echo "%fn%" does not have a .DAT extension, so is not copied
        goto :eof
      )
      
      :: perform the file copy
      if exist "%source%%fn%" (
        copy "%source%%fn%" "%target%"
      )
      
      goto :eof
      
      ::-----------------------------------------------------------------------------

      BATcher

      Plethora means a lot to me.

    • #1537235

      I think your final paragraph can be put down as “future objective” for the time being!

      Running the risk of me posting just as you are replying, I would ask:
      is there only a single file which starts with “Lot27”
      or could there be multiple files which start “Lot27”, for example
      Lot27_Type3_Product2.dat
      Lot27_Type3_Product7.dat
      Lot27_Type16_Product12.dat
      Lot27_Type16_Product227.dat

      The first option is good, the second would require the entire file list to be read multiple times

      BATcher

      Plethora means a lot to me.

      • #1537236

        is there only a single file which starts with “Lot27”
        or could there be multiple files which start “Lot27”, for example

        Yes, multiple files for each lot. I need to grab all files for a given lot name. For example, a single lot has 4 different measurement types, so it will have 4 files related to that lot. Is there a way to search/copy a wildcard? search/copy Lot27* and grabs all the files that match that name?

        • #1537255

          Have a look at

          Code:
          @echo off
          
          :: Copy all the Lotnn_*.dat files 
          ::   whose Lot numbers appear in the text file  filelist.txt
          ::     (which is assumed to be in the source folder)   
          ::  from the source folder  d:datafolder
          ::  to   the target folder  d:transferbackup_lotsyyyymmdd-hrmn
          
          :: filelist.txt entries are expected to look rather like:
          ::   Lot1
          ::   Lot3
          ::   lot15
          ::   LoT1234567
          ::     ... and so on - they do not have to be in ascending order
          
          :: no error-checking is done, thus it is assumed that 
          ::   * the contents of filelist.txt are as expected
          ::   * the source directory exists and contains many Lot*.dat files
          ::   ... and so on
          
          setlocal
          
          :: obtain the current date and time regardless of locale/region/country
          ::   %yy% will contain four digits, 20nn;
          ::   %mm%, %dd% and time variables %hr%, %mn%, %sc% and %th% contain two digits
          if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
          for /f "skip=1 tokens=2-4 delims=(-)" %%a in ('echo.^|date') do (
             for /f "tokens=%toks% delims=.-/ " %%e in ('date /t')     do (
                for /f "tokens=5-8 delims=:., " %%i in ('echo.^|time') do (
                  (set %%a=%%e) & (set %%b=%%f) & (set %%c=%%g) & rem create yy, mm, dd
                  (set hr=%%i)  & (set mn=%%j)  & (set sc=%%k)  & (set th=%%l)
                  rem  note the variable names for Time: hr, mn, sc, th
          )))
          if 1%hr% LSS 20  (set hr=0%hr%)  & :: ensure 2-digit hours in %hr%
          
          :: obtain the full target directory path 
          ::   with the final directory name in the form  yyyymmdd-hrmn  (eg 20151114-1523)
          set target=d:transferbackup_lots%yy%%mm%%dd%-%hr%%mn%
          
          :: create the full target directory path, ignoring any error message
          md %target% 2>nul
          
          :: set up the full source path
          set source=d:data_folder
          
          :: the clever bit: read filelist.txt and, for each Lot number found on a line, 
          ::   copy all the corresponding files from the source path to the target path
          ::   copying is done with the underscore added to prevent redundant copies
          ::     (by that I mean that 'copy Lot1*.dat' would also copy all of 'Lot12_*.dat', etc)
          for /f "tokens=*" %%a in (filelist.txt) do (
            copy "%source%%%a_*.dat" "%target%"
          )
          
          :: that's it, folks!  (maybe a directory list would be useful...?)
          
          pause
          
          endlocal
          
          exit /b 0
          

          Tested!

          The answer to your question depends on what proportion of files will be copied as opposed to the total number of file.
          I would reckon that it’s best to copy ONLY those files which are wanted!

          BATcher

          Plethora means a lot to me.

          • #1537257

            Tested!

            I tested it too, on my local machine, and it works too. AWESOME! I’m having a bit of trouble tweaking it to work inside a remote desktop on the network.

            How would you adjust it to have the filelist.txt exist elsewhere? For example, we have personal network drives (Pdrives) that we can access both inside a .rdp and outside, on my local computer. Inside the .rdp, I can access a tool through its IP address (ex: \143.182.###.###cdata_folder), but often we don’t have read/write access, just read-only (no login credentials, just . How would I adjust the code to have the .bat file and the filelist.txt exist on my pdrive and then point towards the given tool’s data folder, for searching?

            man, I feel like I should send you a goodie basket or something.

    • #1537239

      I will have to do a bit of thinking about that one (I can see a few different approaches) and I don’t have any more free time until later…

      BATcher

      Plethora means a lot to me.

    • #1537245

      is it possible/better to copy/paste the entire original folder to the transfer folder then go through and delete a .dat file if it doesn’t match the input search list?

    • #1537260

      To use filelist.txt from a different folder, just put the full path in the FOR statement.
      For example
      for /f “tokens=*” %%a in (\servernamed$somefoldernamefilelist.txt) do (
      I’ve never used an IP address in this context, but “why don’t you try it?” !

      The BATch file can probably liv anywhere, provided the file paths are still correct / accessible.

      BATcher

      Plethora means a lot to me.

      • #1537272

        I’ve never used an IP address in this context, but “why don’t you try it?” !

        OK, so I got it to work inside the network .rdp space. I’ve got the batch files and the lotlist.txt file saved in my personal folder, then it points to the ipaddresscdrivedata_folder and grabs it. It works! woo!

        So I made one batch file for each IP Address (each network drive). In order to have a single .bat file that will scan all the ip address drives, do I just repeat the section of code, changing the IP address?

        Code:
        @echo off
        
        :: Copy all the Lotnn_*.dat files 
        ::   whose Lot numbers appear in the text file  filelist.txt
        ::     (which is assumed to be in the source folder)   
        ::  from the source folder  \143.182.###.###c_driveData_Folder
        ::  to   the target folder  D:ProfilesnameDesktopTransferBackupsyyyymmdd-hrmn
        
        :: filelist.txt entries are expected to look rather like:
        ::   Lot1
        ::   Lot3
        ::   lot15
        ::   LoT1234567
        ::     ... and so on - they do not have to be in ascending order
        
        :: no error-checking is done, thus it is assumed that 
        ::   * the contents of filelist.txt are as expected
        ::   * the source directory exists and contains many Lot*.dat files
        ::   ... and so on
        
        setlocal
        
        :: obtain the current date and time regardless of locale/region/country
        ::   %yy% will contain four digits, 20nn;
        ::   %mm%, %dd% and time variables %hr%, %mn%, %sc% and %th% contain two digits
        if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
        for /f "skip=1 tokens=2-4 delims=(-)" %%a in ('echo.^|date') do (
           for /f "tokens=%toks% delims=.-/ " %%e in ('date /t')     do (
              for /f "tokens=5-8 delims=:., " %%i in ('echo.^|time') do (
                (set %%a=%%e) & (set %%b=%%f) & (set %%c=%%g) & rem create yy, mm, dd
                (set hr=%%i)  & (set mn=%%j)  & (set sc=%%k)  & (set th=%%l)
                rem  note the variable names for Time: hr, mn, sc, th
        )))
        if 1%hr% LSS 20  (set hr=0%hr%)  & :: ensure 2-digit hours in %hr%
        
        :: obtain the full target directory path 
        ::   with the final directory name in the form  yyyymmdd-hrmn  (eg 20151114-1523)
        set target=D:ProfilesnameDesktopTransferBackups%yy%%mm%%dd%-%hr%%mn%
        
        :: create the full target directory path, ignoring any error message
        md %target% 2>nul
        
        :: set up the full source path
        set source=\143.182.###.###c_driveData_Folder
        
        :: the clever bit: read filelist.txt and, for each Lot number found on a line, 
        ::   copy all the corresponding files from the source path to the target path
        ::   copying is done with the underscore added to prevent redundant copies
        ::     (by that I mean that 'copy Lot1*.dat' would also copy all of 'Lot12_*.dat', etc)
        for /f "tokens=*" %%a in (D:ProfilesnameDesktopTransferBackupsfilelist.txt) do (
          copy "%source%%%a_*.dat" "%target%"
        )
        
        :: that's it, folks!  (maybe a directory list would be useful...?)
        
        pause
        
        endlocal
        
        exit /b 0
        
        • #1537278

          So I made one batch file for each IP Address (each network drive). In order to have a single .bat file that will scan all the ip address drives, do I just repeat the section of code, changing the IP address?[/quote]

          I got it to work. Awesome! so now, what’s powershell? What’s the differences and pros, cons over batch files? Someone else advised maybe doing this in VB script?

          Code:
          @echo off
          
          :: Copy all the Lotnn_*.dat files 
          ::   whose Lot numbers appear in the text file  filelist.txt
          ::     (which is assumed to be in the source folder)   
          ::  from the source folder  \143.182.###.##1c_drivedata_folder
          ::  to   the target folder  D:ProfilesnameDesktopTransferBackupsyyyymmdd-hrmn
          
          :: filelist.txt entries are expected to look rather like:
          ::   Lot1
          ::   Lot3
          ::   lot15
          ::   LoT1234567
          ::     ... and so on - they do not have to be in ascending order
          
          :: no error-checking is done, thus it is assumed that 
          ::   * the contents of filelist.txt are as expected
          ::   * the source directory exists and contains many Lot*.dat files
          ::   ... and so on
          
          setlocal
          
          :: obtain the current date and time regardless of locale/region/country
          ::   %yy% will contain four digits, 20nn;
          ::   %mm%, %dd% and time variables %hr%, %mn%, %sc% and %th% contain two digits
          if "%date%A" LSS "A" (set toks=1-3) else (set toks=2-4)
          for /f "skip=1 tokens=2-4 delims=(-)" %%a in ('echo.^|date') do (
             for /f "tokens=%toks% delims=.-/ " %%e in ('date /t')     do (
                for /f "tokens=5-8 delims=:., " %%i in ('echo.^|time') do (
                  (set %%a=%%e) & (set %%b=%%f) & (set %%c=%%g) & rem create yy, mm, dd
                  (set hr=%%i)  & (set mn=%%j)  & (set sc=%%k)  & (set th=%%l)
                  rem  note the variable names for Time: hr, mn, sc, th
          )))
          if 1%hr% LSS 20  (set hr=0%hr%)  & :: ensure 2-digit hours in %hr%
          
          :: obtain the full target directory path 
          ::   with the final directory name in the form  yyyymmdd-hrmn  (eg 20151114-1523)
          set target=D:ProfilesnameDesktopTransferBackups%yy%%mm%%dd%-%hr%%mn%
          
          :: create the full target directory path, ignoring any error message
          md %target% 2>nul
          
          :: the clever bit: read filelist.txt and, for each Lot number found on a line, 
          ::   copy all the corresponding files from the source path to the target path
          ::   copying is done with the underscore added to prevent redundant copies
          ::     (by that I mean that 'copy Lot1*.dat' would also copy all of 'Lot12_*.dat', etc)
          
          :: set up the full source path
          set source=\143.182.###.##1c_drivedata_folder
          for /f "tokens=*" %%a in (D:ProfilesnameDesktopTransferBackupsfilelist.txt) do (
            copy "%source%%%a_*.dat" "%target%"
          )
          
          :: set up the full source path
          set source=\143.182.###.##2c_drivedata_folder
          for /f "tokens=*" %%a in (D:ProfilesnameDesktopTransferBackupsfilelist.txt) do (
            copy "%source%%%a_*.dat" "%target%"
          )
          
          :: set up the full source path
          set source=\143.182.###.##3c_drivedata_folder
          for /f "tokens=*" %%a in (D:ProfilesnameDesktopTransferBackupsfilelist.txt) do (
            copy "%source%%%a_*.dat" "%target%"
          )
          
          :: that's it, folks!  (maybe a directory list would be useful...?)
          
          pause
          
          endlocal
          
          exit /b 0
          
    • #1537266

      Surfer,

      Here’s some PowerShell code which will work on the local machine:

      Code:
      Clear-Host
      
      $LotList     = @("V1","V2")
      $Source      = "G:BEKDocsScripts*.ps1"
      $Destination = "G:BEKDocsTransfer"
      
      For ( $i = 0 ; $i -le ($LotList.count -1) ; $i++) { 
        Get-Childitem $Source | Select Name, FullName |
           Where-Object Name -Match "$($LotList[$i])" | 
           ForEach-Object {
              Copy-Item -Path $_.FullName  -Destination $Destination -Force
           }
      }  #End For
      

      Results from a directory tree containing 699 files in 68 folders:
      42625-pscopy

      You’ll notice I used Version numbers vs Lot numbers but that is because I had files in that format to test with you would just need to change the $LotNumbers array to @(“Lot1_”,Lot43_”, … etc.) You could also read this array from a file.

      Being PowerShell this could be adapted to run in the network space using the Start-Process & -computer parameter but I’m currently traveling and only have my laptop, .i.e. no network available to test.

      The destination can also be coded to create a directory based on date/time or any other compuetable value and then create it.

      You’ll also notice that no pre existing file list is necessary!

      If you are interested in persuing this post back and I’ll continue development of the concept (maybe others will assist … please).

      HTH :cheers:

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

      • #1537270

        If you are interested in persuing this post back and I’ll continue development of the concept (maybe others will assist … please).

        Awesome! So I’m pretty clueless as to powershell and how to use it. Can we chat more? PM or stay public in this thread? Up to you.

        BATcher: I’ll try to make these adjustments and let you know soon. Lots of meetings today….

    • #1537271

      Surfer,

      Let’s keep it in the thread so all may benefit and/or contribute.

      I’ll work w/BATcher’s code to get the destination folder part of it coded. I won’t be able to get to the multiple computer part till I return home mid-week. Do you already have Access to these machines via shares or do you have to access the machines via RDP?

      :cheers:

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

    • #1537318

      Here’s the same thing with a bit less stuff around the edges (you’ve got me doing PS now!).

      cheers, Paul

      Code:
      $LotList     = @(“V1″,”V2”)
      $Source      = “G:BEKDocsScripts*.ps1”
      $Destination = “G:BEKDocsTransfer”
      
      foreach ($Val in $LotList) {
        @(Get-Childitem $Source).Where{$_.Name -Match $Val} |
        Copy-Item -Path $_.FullName  -Destination $Destination -Force
      }
    • #1537319

      PowerShell is generally more powerful than Batch files, but it’s also more complex as it works with objects, not text based like Batch. I’d use PowerShell over VBS these days just because it’s the current interpreted language and therefore worth learning.

      cheers, Paul

    • #1537340

      It looks like one of the advantages of BATch file scripting over PowerShell is that people tend to explain what they’re doing!

      PowerShell seems to bear some similarities to APL, which was notoriously opaque – almost a “Write-Only Language“!

      BATcher

      Plethora means a lot to me.

      • #1537374

        PowerShell seems to bear some similarities to APL, which was notoriously opaque – almost a “Write-Only Language“!

        BATcher,

        Looks a bit like:

        Code:
        Set Pot=Black
        Set Kettle=Black
        If %Kettle%==%Pot% (Echo. True) Else (Echo. False)
        

        35623-ROTFLOL
        :cheers:

        May the Forces of good computing be with you!

        RG

        PowerShell & VBA Rule!
        Computer Specs

      • #1537499

        It looks like one of the advantages of BATch file scripting over PowerShell is that people tend to explain what they’re doing!

        PowerShell seems to bear some similarities to APL, which was notoriously opaque – almost a “Write-Only Language“!

        APL OMG used all the time share I had at university playing BlackJack 😀 :cheers:

        🍻

        Just because you don't know where you are going doesn't mean any road will get you there.
    • #1537387

      BATcher

      Plethora means a lot to me.

    • #1537400

      BATcher,

      How’s this for clarity?

      Code:
      Clear-Host
      
      #Path to spec files, e.g. Lotlist.txt & Sources.txt
      $SpecPath = "G:BEKDocsScripts"
      
      #Load contents of text file file into array LotList - one lot per line
      $LotList     = Get-Content -Path "$($SpecPath)LotList.txt"
      
      #Load contents of text file file into array Sources - one source directory path per line
      $Sources     = Get-Content -Path "$($SpecPath)Sources.txt"
      
      #Where to put copies of selected files
      $Destination = "G:BEKDocsTransfer"
      
      ForEach ( $Src in $Sources) {               #Loop through Sources Array
      
         ForEach ( $Val in $LotList) {            #Loop through LotList Array
      
            Get-Childitem $Src |                  #Get files in $Src
            Select Name, FullName |               #Select only necessary properties from object
            Where-Object Name -Match "$($Val)" |  #Select only items matching item in LotList
               ForEach-Object {                   #Loop through matching files and copy
                     Copy-Item -Path $_.FullName `
                               -Destination "$($Destination)$($_.Name)" -Force
               } #End ForEach-Object
      
         }  #End ForEach ($Val
      
      } #End ForEach ($Src
      

      Borrowed a little from Paul T but didn’t want to make it impossible to comment (his was very nice code!).

      Next step Create Parameters to pass the SpecPath & Destination paths into the program and if not passed let user select from list.

      I’d appreciate it if someone with some Network Shares could test with them added into the Sources.txt file.

      Here’s the test files so you have an idea of what I used. 42635-Test-FIles

      HTH :cheers:

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

    • #1537440

      Better! 8/10!

      BATcher

      Plethora means a lot to me.

    • #1537580

      so how do I implement powershell code?
      #clueless

    • #1537589

      Start PowerShell, same as Command Prompt – Start > Run > powershell.
      Type the stuff you want to run.
      To run a script you need to do a little more, see this thread. http://windowsitpro.com/powershell/running-powershell-scripts-easy-1-2-3

      cheers, Paul

    • #1537805

      Surfer,

      Next version:

      This version allows you to pass parameters as to the location of the specification files (Sources & LotList) and the Destination directory as follows:

      Code:
      PS> .Copy-SelectedFilesV2.ps1 -SpecPath "G:BEKDocsScripts" -Destination "G:Test"

      If either parameter is omitted you will be prompted for it via a standard dialog box.
      42679-SourcesPicker 42678-DestinationPicker

      Code:
      Param (
              #Path to spec files, e.g. Lotlist.txt & Sources.txt
         [Parameter (Mandatory=$False)]
             [String] $SpecPath ,   
              #Where to put copies of selected files
        [Parameter (Mandatory=$False)]
             [String] $Destination 
      )
      
      Clear-Host
      
      #$FileBrowser   = New-Object Windows.Forms.OpenFileDialog
      $FolderBrowser = New-Object Windows.Forms.FolderBrowserDialog
      $FolderBrowser.RootFolder = [System.Environment+SpecialFolder]'MYDocuments'
      $FolderBrowser.ShowNewFolderButton=$True
      $FolderBrowser.Description = 'Pick a Path to the LotList && Sources .txt files:'
      
      #If no SpecPath argument supplied display folder picker
      If ($SpecPath -eq "") {
        If ($FolderBrowser.ShowDialog() -ne 'OK') { Exit }
        $SpecPath = $FolderBrowser.SelectedPath
        $FolderBrowser.Reset()                   #Clear SelectedPath
      }
      
      #If no Destination Path argument supplied display folder picker
      $FolderBrowser.RootFolder = [System.Environment+SpecialFolder]'MYDocuments'
      $FolderBrowser.Description = 'Pick the destination for the copied files:'
      
      If ($Destination -eq "") {
        If ($FolderBrowser.ShowDialog() -ne 'OK') { Exit }
        $Destination = $FolderBrowser.SelectedPath
      }
      
      #Load contents of text file file into array LotList - one lot per line
      $LotList     = Get-Content -Path "$($SpecPath)LotList.txt"
      
      #Load contents of text file file into array Sources - one Drive/Path per line
      $Sources     = Get-Content -Path "$($SpecPath)Sources.txt"
      
      ForEach ( $Src in $Sources) {               #Loop through Sources Array
      
         ForEach ( $Val in $LotList) {            #Loop through LotList Array
      
            Get-Childitem $Src |                  #Get files in $Src
            Select Name, FullName |               #Select only necessary properties from object
            Where-Object Name -Match "$($Val)" |  #Select only items matching item in LotList
               ForEach-Object {                   #Loop through matching files and copy
                     Copy-Item -Path $_.FullName `
                               -Destination "$($Destination)$($_.Name)" -Force
               } #End ForEach-Object
      
         }  #End ForEach ($Val
      
      } #End ForEach ($Src
      

      I’ve tested this on my WD MyBookLive NAS box and it works so it should work with any shares you have access to (of course this should still be tested).

      If you need help setting up PowerShell see this post:

      File: 42680-Copy-SelectedFilesV2

      I’d suggest testing with PowerShell ISE.exe

      HTH :cheers:

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

    • #1537810

      Surfer,

      A slightly improved version that will check your passed parameters and if either is invalid it will display the appropriate picker dialog.

      File: 42682-Copy-SelectedFilesV3

      HTH :cheers:

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

      • #1537924

        @retiredgeek: how did you get it to run? I loaded it into the PS ISE and runnign the green start button, but nothing happens. It looks like its supposed to prompt a popup, right, where you identify the file directories?

    • #1537928

      Surfer,

      Open the PS ISE.
      Type in the right hand window (if you have two): Set-ExecutionPolicy RemoteSigned
      Then: Get-ExecutionPolicy

      It should return: RemoteSigned.

      If you don’t have two windows click the icon at the top to get the second (code windows).
      Paste the code from my post into this window.
      Click the Green Arrow.
      Note: You may need to minimize the PS ISE window to see the directory picker!

      OR

      You can Save the file as yourname.ps1
      Then in the left window type the command in post#35.

      42689-surfer

      HTH :cheers:

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

    • #1538086
      Code:
      PS P:> Get-ExecutionPolicy
      RemoteSigned
      
      _______________________________________________________________________________________
      PS P:> P:transferutilityCopy-SelectedFilesV3.ps1
      Cannot find the type for custom attribute 'Parameter '. Make sure that the assembly that cont
      ains this type is loaded.
      At P:transferutilityCopy-SelectedFilesV3.ps1:3 char:15
      +    [Parameter  <<<< (Mandatory=$False)]
          + CategoryInfo          : InvalidOperation: (Parameter :Token) [], ParentContainsErrorRec
      ordException
          + FullyQualifiedErrorId : CustomAttributeTypeNotFound
    • #1538107

      Surfer,

      My bad! I forgot that I had certain assemblies loaded in my PSProfile.

      Add this line right after the Clear-Host line:

      Code:
      Add-Type -AssemblyName System.Windows.Forms
      

      HTH :cheers:

      May the Forces of good computing be with you!

      RG

      PowerShell & VBA Rule!
      Computer Specs

    • #1538143

      Bad RG, very bad!

      cheers, Paul

    Viewing 25 reply threads
    Reply To: Batch File: search list of names, copy any file containing one of those names?

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: