Reputation: 129
I am trying to iterate over a set of folders and copy them to a different location in PowerShell. All the folders follow the following naming convention:
20160621
This is obviously the day written in yyyymmdd
format. Since all of the folders follow this convention, my question is how would I say: copy all the folders from the past week"? I have thought of using (get-date).AddDays(-7)
but I am unsure how to recognize the folder names as date objects and not strings.
Upvotes: 1
Views: 294
Reputation: 58931
Just use the Get-ChildItem cmdlet to retrieve the files and filter them using the Where-Object cmdlet.
The following script combines three Where
conditions
DateTime
object and ensure its earlier then seven days ago:Script:
Get-ChildItem 'your_source' | Where-Object {
$_.PsIsContainer -and
$_.BaseName -match '\d{6}' -and
([DateTime]::ParseExact($_.BaseName, 'yyyyMMdd', $null) -gt (Get-Date).AddDays(-7))
} | Copy-Item -Destination 'Your_destination'
Upvotes: 1