0

我有一个文件夹,其中包含子文件夹,每个子文件夹都有许多 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
   }
}
4

1 回答 1

0

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

因为您也使用-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
}

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

于 2019-11-23T14:53:02.597 回答