I am new to power shell, I am trying to copy files from one location to another between specific dates.
I have an issue with the dates part it seems to be copying all the files regardless of the dates, any idea why?
$StartDate = (Get-date).Addyears(-2)
$EndDate = (Get-date).Adddays(-2)
$src = "C:\Sites\T\Test01"
$dst = "C:\Customer\"
Get-ChildItem $src -exclude "Aeromark" -Recurse | Copy-Item -Destination $dst -Force |
Where-Object {($_.LastWriteTime.Date -ge $StartDate.Date) -and ($_.LastWriteTime.Date -le $EndDate.Date)}
Where-Object
needs to go before Copy-Item
in your particular case. The Copy-Item
command is being called before Where-Object
excludes the files based on date.
Here is your code re-arranged:
Get-ChildItem $src -exclude "Aeromark" -Recurse |
Where-Object {($_.LastWriteTime.Date -ge $StartDate.Date) -and ($_.LastWriteTime.Date -le $EndDate.Date)} |
Copy-Item -Destination $dst -Force