Question

I have two question or a two part problem:

  1. I have a CSV file with a list of files including full path, e.g.:

    C:\file1.txt
    C:\file2.xls
    C:\file3.doc
    etc.
    

    I need to check the modified date for each file and if its within a specific timespan, then output it to a new CSV file, e.g.:

    C:\file1.txt has modified time and date 01/01/2014 10:00
    C:\file2.xls has modified time and date 02/01/2014 12:00
    C:\file3.doc has modified time and date 03/01/2014 14:00
    C:\file4.ppt has modified time and date 04/01/2014 16:00
    

    Timespan = 02/01/2014 8:00 to 03/01/2014 20:00

    The output.csv file should contain:

    C:\file2.xls
    C:\file3.doc
    

    I've tried to modified existing PowerShell scripts I've found online, but honestly don't understand the code. I've tried using foreach-object:

    $names = get-content .\test.csv
    $names | foreach-object {(get-item $_.name).lastwritetime}
    

    but I'm falling over at job getting this to work.

  2. I then need to pass the output.csv file to robocopy, which doesn't support it natively so might need to use a loop to call robocopy, to copy files from one location to another.

Hope this makes sense.

Was it helpful?

Solution

Observe that the solution below will not work if there are several files with the same file name. The only thing you'll need to add then is some form of source base address (from which the file structure is built) and a destination base address and just build the new destination path based on these.

$copyChangesSince = Get-Date "2014-01-08"
$doNotCopyChangesNewerThan = Get-Date "2014-02-02"
get-content .\files.txt | Foreach {
        Get-Item $_
    } |
    Where { $_.LastWriteTime -gt $copyChangesSince -AND $_.LastWriteTime -lt $doNotCopyChangesNewerThan } |
    Select FullName, Name |
    Export-Csv C:\temp\filelist.csv -NoTypeInformation

Since you only want to copy a single item at a time I'm not sure I see the benefit of using robocopy. In my example below, I've just used Copy-Item. If you really want to use robocopy it shouldn't be hard to replace that call with a call to robocopy.

Import-Csv C:\temp\filelist.csv |
    Foreach { Copy-Item -Path $_.FullName -Destination "C:\temp\output\$($_.Name)" }

If you don't want to actually use the .csv-file afterwards, you could just as easily skip that part and replace the Select and Export-Csv with the Foreach statement from the Import-part (and of course skip the Import-Csv as well).

Edit: Split the process into two parts, as was requested in the question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top