在 Powershell 中遍历文件

Iterate over files in Powershell

我正在尝试遍历一组文件夹并将它们复制到 PowerShell 中的不同位置。所有文件夹都遵循以下命名约定:

20160621

这显然是用yyyymmdd格式写的日子。由于所有文件夹都遵循此约定,我的问题是我怎么说:复制过去一周的所有文件夹“?我想过使用 (get-date).AddDays(-7) 但我不确定如何将文件夹名称识别为日期对象而不是字符串。

只需使用 Get-ChildItem cmdlet to retrieve the files and filter them using the Where-Object cmdlet。

下面的脚本结合了三个Where条件

  1. 获取所有目录
  2. 确保目录名称正好包含六位数字。
  3. 将六位数字解析为一个DateTime对象并确保其早于7天前:

脚本:

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'