Link to home
Start Free TrialLog in
Avatar of samiam41
samiam41Flag for United States of America

asked on

PS Script copy files based on modified date

Hey Experts.  Trying to get this script to back up only the files that have a modified date of 12 days or less/newer.  Help is appreciated as I've tried blending together a couple of scripts I found on the web.

$TimeStamp = get-date -f yyyyMMddhhmm
$Destination = "Y:\BACKUP_" + $TimeStamp
$Source = "X:\folder"
$Max_days = "-14"
$Curr_Date = get-date

Foreach($file in (Get-ChildItem $Source))
{
    if($file.LastWriteTime -gt ($Curr_date).adddays($Max_days))
    {
        New-Item -ItemType directory -Path $Destination -Force
        Copy-Item -Path $Source\*.* -Destination $Destination -Force 
    }
    ELSE
    { "not copying $file"
    }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of samiam41

ASKER

Thank oBdA!  Here is what I get when I run it:


At Z:\Scripts\PRTG_Backup.ps1:8 char:37
+ $newerThan = (Get-Date).AddDays(-1 * max_days)
+                                     ~
You must provide a value expression following the '*' operator.
At Z:\Scripts\PRTG_Backup.ps1:8 char:37
+ $newerThan = (Get-Date).AddDays(-1 * max_days)
+                                     ~
Missing ')' in method call.
At Z:\Scripts\PRTG_Backup.ps1:8 char:38
+ $newerThan = (Get-Date).AddDays(-1 * max_days)
+                                      ~~~~~~~~
Unexpected token 'max_days' in expression or statement.
At Z:\Scripts\PRTG_Backup.ps1:8 char:46
+ $newerThan = (Get-Date).AddDays(-1 * max_days)
+                                              ~
Unexpected token ')' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpectedValueExpression

Avatar of oBdA
oBdA

Sorry, a $ went AWOL.
Edited above, just download the script again.

$daterange = $(get-date).AddDays(-14).ToString("dd/MM/yyyy")


I plugged that in so it would compare date values in a similar manner.  If you'd like to offer up a tweak to your script, please do.  Thanks oBdA

I found the opps.  Line 7, the max_days variable is missing the $.  

That worked!  Solid job.  Is there a way for you to submit the corrected version of your script so I can select it as the right answer?

Sorry, can't quite follow you with the $daterange = $(get-date).AddDays(-14).ToString("dd/MM/yyyy")
You can't do date comparison with strings in this format.

I already edited the script above.
And I hate the new font EE is now using, where you have to look twice to tell a $ from a S ...