Use the Get-ChildItem cmdlet in PowerShell to get the items from the specified location and the Get-Date cmdlet to calculate the cut-off date to retrieve files later than the cut-off date. Use the Copy-Item cmdlet to copy files newer than a date to the destination folder.
While working with files and directories, we need to copy only the most recent files or copy files based on their age. PowerShell provides cmdlets for managing files and folders.
In this article, we will discuss how to copy files newer than the date and copy files based on the modified date to the destination folder using the combination of Get-ChildItem, Get-/Date, and Copy-Item cmdlets in PowerShell.
Get Files Newer Than a Specific Date
Use the Get-ChildItem cmdlet to retrieve a list of files and the Where-Object cmdlet to filter based on a specific date.
# Specify the directory $sourceFilePath = "D:\PS" # Specify the cut off date $daysOld = 7 $cutoffDate = (Get-Date).AddDays(-$daysOld) # Retrieve files newer than a specific date $NewFiles = Get-ChildItem -Path $sourceFilePath -File | Where-Object {$_.LastWriteTime -gt $cutoffDate}
In the above PowerShell script, we have defined a source file folder path and stored it in the variable $sourceFilePath
. Then, we use the Get-Date cmdlet to calculate the cut-off date. The Get-ChildItem command uses the -Path
parameter to list the files from the specified directory and filter the results using the Where-Object to get files with a LastWriteTime attribute later than the cut-off date.
The output of the above PowerShell script to retrieve files based on the date is:
Copy Files Newer Than Date
Use the Copy-Item cmdlet to copy the files retrieved using the Get-ChildItem command based on their last modified date.
# Specify the destination folder to copy files $destinationFolder = "D:\PS\temp" # Copy files modified after certain date $NewFiles | ForEach-Object { Copy-Item -Path $_.FullName -Destination $destinationFolder} # Get the files from the destination folder Get-ChildItem -Path $destinationFolder -File
In the above PowerShell script, the $destinatonFolder
variable stores the destination directory location where files will be copied.
The $NewFiles
variable contains the list of files retrieved based on the last write and it sends the output to ForEach-Object
iterate each file and uses Copy-Item to copy files based on the modified date to the destination folder.
The output of the above PowerShell script after copying files modified after a certain date with filter is:
Conclusion
I hope the above article on how to use PowerShell to copy files newer than data is helpful to you.
The combination of Get-ChildItem, Get-Date, Where-Object, and Copy-Item cmdlets in PowerShell can help to get a list of files modified or created in the date range and transfer only the most recent files.
You can find more topics about PowerShell Active Directory commands and PowerShell basics on the ShellGeek home page.