将子目录中的所有xls文件都归档,然后根据文件创建日期将其移动到文件夹中

问题描述 投票:0回答:1

我有一个包含子文件夹的文件夹,每个子文件夹都包含许多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个回答
0
投票

不需要先在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
}

Move-Item末尾的-WhatIf开关用于测试。对consoe中显示的文本满意后,请删除该开关,以开始实际移动文件。

© www.soinside.com 2019 - 2024. All rights reserved.