I'm trying to copy files in a folder to another folder according to the date modified but the code keeps copying all files in the source folder to the destination folder.
New-Item -Path $psScriptRoot\ArchiveTest -ItemType Directory
compress-Archive -Path $PSScriptRoot\*.txt -DestinationPath $PSScriptRoot\ArchiveTest | Where-Object LastWriteTime -Like "*2010*"
I've tried changing the Syntax of the where-Object cmdlet. When I use the Get-Item cmdlet with the exact same Where-Object i get the correct output.
The end goal is to archive the files in a folder according to year, so for instance:
Items in folder:
Mode LastWriteTime Length Name
-a---- 2010/02/15 15:23 39590 Test5.txt -a---- 2010/02/24 17:43 690581 Test5.txt -a---- 2012/04/12 11:46 105086 Test5.txt -a---- 2015/05/10 15:46 15952531 Test5.txt -a---- 2015/05/12 09:27 453365 Test5.txt
What I want to end with in the folder:
Mode LastWriteTime Length Name
d----- 2023/01/10 11:35 2010 -----
d----- 2023/01/10 11:35 2012 ------- (Zip Folders)
d----- 2023/01/10 11:35 2015 -----/
CodePudding user response:
Here is how to do it:
Get-ChildItem -Path $PSScriptRoot -Filter "*.txt" | Where-Object { $_.LastWriteTime.Year -eq "2022" } | Compress-Archive -DestinationPath "$PSScriptRoot\archive_2022.zip"
Here is how to do it in a loop for several years:
$startYear = 2001;
$endYear = 2020;
for ($year = $startYear; $year -le $endYear; $year ) {
Get-ChildItem -Path $PSScriptRoot -Filter "*.txt" | Where-Object { $_.LastWriteTime.Year -eq $year } | Compress-Archive -DestinationPath "$PSScriptRoot\archive_$year.zip"
}