【问题标题】:Fild all xls files in subdirectories and move them to a folder based on file creation date查找子目录中的所有 xls 文件,并根据文件创建日期将它们移动到文件夹中
【发布时间】:2019-11-22 20:21:25
【问题描述】:

我有一个文件夹,其中包含多个子文件夹,每个子文件夹都有许多 Excel 电子表格。我试图让powershell搜索子目录,然后将所有具有相同创建日期的xls文件移动到该创建日期的新文件夹中。我很接近我认为这是我的代码。发生的事情是它只查看“报告”中的文件,而不是“报告”的子文件夹。

Get-ChildItem "c:\users\username\documents\reporting\*.xls" -Recurse | foreach {
$x = $_.LastWriteTime.ToShortDateString()
$new_folder_name = Get-Date $x -Format yyyy.MM.dd
$des_path = "c:\users\username\documents\$new_folder_name"

if (test-path $des_path){
   move-item $_.fullname $des_path
   } else {
   new-item -ItemType directory -Path $des_path
   move-item $_.fullname $des_path
   }
}

【问题讨论】:

    标签: powershell subdirectory datecreated


    【解决方案1】:

    无需先在 LastWriteTime 属性上使用ToShortDateString(),然后使用它重新创建日期以对其进行格式化。

    因为您也使用-Recurse 开关来搜索子文件夹,所以代码也可以调整为-Include 参数,如:

    $sourcePath = 'c:\users\username\documents\reporting'
    $targetPath = 'c:\users\username\documents'
    Get-ChildItem $sourcePath -Include '*.xls', '*.xlsx' -File -Recurse | ForEach-Object {
        $des_path = Join-Path -Path $targetPath -ChildPath ('{0:yyyy.MM.dd}' -f $_.LastWriteTime)
        if (!(Test-Path -Path $des_path -PathType Container)) {
            # if the destination folder does not exist, create it
            $null = New-Item -Path $des_path -ItemType Directory
        }
        $_ | Move-Item -Destination $des_path -Force -WhatIf
    }
    

    移动项目末尾的-WhatIf 开关用于测试。一旦您对控制台中显示的文本感到满意,请移除该开关以实际开始移动文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多