Powershell script is moving wrong files based on lastwritetime

803 views Asked by At

I have a powershell script that moves files from one folder to the other using the lastwritetime of the file. The script is checking to see if the lastwritetime is less than or equal to a specified date. It seems with the year change this is no longer working correctly. I have files with a date modified of 12/29/2016, 12/30/2016, and 1/2/2017. The 12/29 files should have been the only ones moved since today is 1/3/2017 and the script is using that date minus 5 days. So, it should have only moved anything less than or equal to 12/29/2016. But, the 1/2/2017 files were also moved. The script is below, any ideas on why this is occurring.

#Grab the day of the week it is TODAY
$DayofWeek = (Get-Date).DayofWeek

#Set the location we are going to be Pulling Files From
$FromPath = "path i'm copying files from goes here"

#Set the Location we are going to copy file To
$ToPath = "path i'm copying files to"

#Set a Default Value for DaysBack to Zero
$DaysBack = 0

#Set the Days Back if it is Tuesday through Friday
switch ($DayofWeek)
{
    "Tuesday"   { $DaysBack = -5 }
    "Wednesday" { $DaysBack = -5 }
    "Thursday"  { $DaysBack = -3 }
    "Friday"    { $DaysBack = -3 }
    "Saturday"  { $DaysBack = -3 }

    #If today is not an above day then tell the user today no files should be moved
    default     { Write-host "No files to move!" }
}

#if DaysBack does not equal ZERO then there are files that need to be moved!
if($DaysBack -ne 0) {
    Get-ChildItem -Path $FromPath |
    Where-Object { $_.LastWriteTime.ToString("MMddyyyy") -le (Get-Date).AddDays($DaysBack).ToString("MMddyyyy") } |
    Move-Item -Destination $ToPath
}
1

There are 1 answers

2
sodawillow On BEST ANSWER
$date1 = Get-Date -Year 2017 -Month 1 -Day 2
$date2 = Get-Date -Year 2016 -Month 12 -Day 29

$date1 -gt $date2
#returns True

$date1.ToString("MMddyyyy") -gt $date2.ToString("MMddyyyy")
# "01022017" -gt "12292016"
# returns False

You can use

if($DaysBack -ne 0) {
    Get-ChildItem -Path $FromPath |
    Where-Object { $_.LastWriteTime -le (Get-Date).AddDays($DaysBack) } |
    Move-Item -Destination $ToPath
}

or

if($DaysBack -ne 0) {
    Get-ChildItem -Path $FromPath |
    Where-Object { $_.LastWriteTime.ToString("yyyyMMdd") -le (Get-Date).AddDays($DaysBack).ToString("yyyyMMdd") } |
    Move-Item -Destination $ToPath
}