Willis Zawisa
Willis Zawisa

Reputation: 129

Iterate over files in Powershell

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

Answers (1)

Martin Brandl
Martin Brandl

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 Whereconditions

  1. Get all directories
  2. Ensure the directory name contains exactly six digits.
  3. Parse the six digits to a 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

Related Questions