October 16, 2021

Software Mile.com

Latest Software News and Hacks

Copy new files based on date in file name

I’ve pieced together this script from various sources to try and get something that:

a) pulls the date from the file name

b) compares the date

c) ensures that the date is from today

d) copies the file

I am able to split the date from the file name. The file name format is,

20210918.001015.file.bin

I tested that part and it works.

I don’t care about the time portion of the file, just the date in yyyyMMdd.

I can’t get the dates to parse correctly so that the math can take place to compare them. I need the most recent files (from ‘today’ or current date). Instead of doing the comparison, it goes ahead and copies all files based on the file filter. What am I doing wrong?

I suspected I wasn’t getting the correct info for $refDate but it does return what I need when I run it separately.

PS C:WINDOWSsystem32> ('{0:yyyyMMdd}' -f (Get-Date).AddDays(-0).Date) 20210919 

Edit: it has to be doing something with the date, because it wouldn’t run just now and I realized I don’t have any files for the new day. Once I put -1 in AddDays(-1) it picked up files but it picked up ALL files not just the ones I wanted.

Thanks in advance for any input.

$refDate = ('{0:yyyyMMdd}' -f (Get-Date).AddDays(-0).Date) # files must be from today $source = 'C:Source' $destination = 'C:Destination' $fileList = '*.FILE.bin' $today = [DateTime]::ParseExact( $refDate, 'yyyyMMdd', $null ) Get-ChildItem -Path 'C:Source' -Filter '*.FILE.bin' -File | ForEach-Object { $DatePart = ( $_.BaseName -split '(d{8})' )[1] $file = $_.BaseName try { $FileDate = [DateTime]::ParseExact( $DatePart, 'yyyyMMdd', $null ) if ($FileDate -ge $today) { $_ | robocopy.exe $source $destination $filelist /is /it /log+:"C:Sourcecopylog.log" } } catch { Write-Warning "File $file contains an invalid date" } } 

submitted by /u/svkadm253
[link] [comments]


Go to Source of this post
Author Of this post: /u/svkadm253
Title Of post: Copy new files based on date in file name
Author Link: {authorlink}