Search code examples
powershellmatchfile-copying

PowerShell Iterate file contents matching filenames recursively in directory


I have a list of filenames organized like so: (search.txt)

2KJ34DS
JSD92NS
1JNKD8A
KO1N231
ASJDOA9

I have a directory organized like so: \\logs\

20161201
  .\
  K2J3N4K.xml
  SDJNFK2.wav
  ASDN1JE.html
20161202
20161203
20161204

The contents of the dated folders in the directory are the filenames I need to match on according to the list provided within the search.txt file.

I need a powershell script that can iterate over the dated folders and copy the file matches it finds to a destination "\\logs\matches\". It should match any file extension. It would be an added bonus if I could specify a "start date" and "end date" and it only iterate between the dated folders within the start and stop date.

I have no idea where to start... can anyone help?


Solution

  • hi try Something like this (PowerShell v3 minimum)

    $listfiles=get-content "c:\temp\search.txt"
    $destination="c:\logs\matches"
    $startdate=get-date -Year 2016 -Month 01 -Day 01 -Hour 0 -Minute 0 -Second 0
    $enddate=get-date -Year 2017 -Month 06 -Day 24 -Hour 0 -Minute 0 -Second 0
    
    Get-ChildItem -file -Recurse "c:\logs" | 
        where {$_.BaseName -in $listfiles -and $_.FullName -ne "$destination\$($_.Name)" -and $_.LastWriteTime -ge $startdate -and $_.LastWriteTime -le $enddate} | 
            Copy-Item  -Destination $destination -Force