如何迭代或循环浏览符合特定条件的文件夹

时间:2019-06-26 21:08:14

标签: windows powershell

我有一个目录,其中包含与日期相对应的文件夹(即带日期的子文件夹)。它们的格式均为yyyymmdd。此目录中还有其他文件夹,其名称为文本。我想做的是编写一个脚本,该脚本将使用户输入他们希望看到多少天。然后,脚本将对每个文件夹执行一些操作。我在弄清楚如何正确获取所有文件夹列表时遇到一些麻烦。

目录如下:

C:--/
    FOO--/
         --20190525
         --20190526
         --20190527
         --20190528
         --20190529
         --20190530
         --20190531
         --20190601
         --20190602
etc.

我当前正在使用for循环,但是问题是当月末发生时,即20190531,循环将继续到20190532,而不是20190601。

$lastday = (Get-Date).AddDays(-1).ToString("yyyyMMdd")
$lastdayint = [int]$lastday
$days = [Microsoft.VisualBasic.Interaction]::InputBox('How many days back do you want to process?')
if ($days.Length -eq 0) {
    Exit
}
$daysint = [int]$days
$firstday = (Get-Date).AddDays(-$daysint).ToString("yyyyMMdd")
$firstdayint = [int]$firstday

for ($i = $firstdayint; $i -le $lastdayint; $i++) {
    # Get our dated sub folder by looking through the root of FOO
    # and finding the folder that matches the condition
    $datedsub = (Get-ChildItem -Path "C:\FOO\*" | Where-Object { ($_.PSIsContainer) -and ($_.Name -eq [string]$i) } ).Name
    # If the path does not exist, both processes will fail, so exit out of the loop and move on to the next date
    if ( $( try { !(Test-Path -Path ("C:\FOO\$datedsub").Trim() -PathType Container) } catch { $false } ) ) {
        Continue
    }
}

我很想弄清楚如何获取名称在2个日期之间的所有文件夹。在CMD脚本中,这很容易做到,因为所有内容都是字符串,并且文件夹没有属性。但是,使用Powershell会更加困难。 脚本需要做的是遍历指定范围内的所有文件夹。我很确定foreach循环可能是我最好的选择,但是我在弄清楚如何设置它方面遇到了麻烦。

2 个答案:

答案 0 :(得分:1)

您应该使用AddDays()遍历实际日期,而不是将字符串转换为整数并递增整数:

$days = [Microsoft.VisualBasic.Interaction]::InputBox('How many days back do you want to process?')
if ($days.Length -eq 0) {
    Exit
}
$startDate = (Get-Date).AddDays(-$days)
$endDate = (Get-Date).AddDays(-1)

for($currentDate = $startDate; $currentDate -le $endDate; $currentDate.AddDays(1)) {
    $dateString = $currentDate.ToString('yyyyMMdd')
    if ( -not( Test-Path "C:\FOO\$dateString" -PathType Container ) ) {
        continue
    }
    # do work here
}

答案 1 :(得分:1)

您的代码可以通过算法简化:

[int]$days = [Microsoft.VisualBasic.Interaction]::InputBox('How many days back do you want to process?')
if ($days.Length -eq 0) {
    Exit
}

# will contain folders
$dirlist = @()

# note: includes today. To not include today, start $i at 1
for ($i = 0; $i -le $days; $i++) {
    $datestr = (Get-Date).AddDays(-$i).ToString("yyyyMMdd")
    $dir = Get-ChildItem -Path $datestr -Directory -ErrorAction SilentlyContinue
    if($null -ne $dir) {
        [void]$dirlist.Add($dir)
        # Or do work here. Otherwise you can use the outputted arraylist
    }
}

# prints folders to console
$dirlist

以上:

  1. 向用户询问返回的天数
  2. 保存该天数并循环多次
  3. 使用“今天”获取日期字符串-$i
  4. 使用Get-ChildItem-Path来查找项目,-Directory来限制目录,-ErrorAction SilentlyContinue来抑制错误(如果不存在,它将返回{{ 1}})
  5. 如果不是$null,则添加到ArrayList