Harlan
Harlan

Reputation: 197

How to copy folders older than a specific date with Powershell 2.0

I have a number of folders that I am trying to copy. The folders are all name 'yyyymmdd' i.e. 20190615, going back up to a year or more. I am trying to figure out a way to copy only the last 45 days of these folders. The biggest issue that I've run into is that the computers that I am running this on only have Powershell 2.0, which seems to have some limitations that 5 or greater does not have.

I have been able to get the list of all of the folders in the path with :

$datedsubs = Get-ChildItem -path $path | where-object { $_ -like "20*" }

From there though, I am a little stuck. I feel this would be easier with PS 5 or greater. I've tried Robocopy, even though that is not a PS solution, but that copies everything, and I just want the folders.

I've tried something like the following, but it doesn't seem to work in PS 2.0.

Get-ChildItem -Path $path | Where-Object { ($_ -like '20*') -and ($_.LastAccessTime -lt $datedlimit)} | Copy-Item -Destination $destination -Recurse

Any help would be appreciated here.

Thanks

Upvotes: 0

Views: 215

Answers (1)

Drew
Drew

Reputation: 4030

Putting what Lee has said into some code.

Get-ChildItem -Path $Path -Filter "20*" | Where-Object {($_.PSIsContainer) `
    -and ($_.LastAccessTime -gt ((Get-Date).AddDays(-45)))} | `
    Copy-Item -Destination $destination -Recurse

This should get you what you are after.

I have put it to -gt 45 days ago because this will only show folders accessed within the last 45 days.

Upvotes: 0

Related Questions