清除子目录中的所有 xls 文件,并根据文件创建日期将它们移动到文件夹中



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

Get-ChildItem "c:usersusernamedocumentsreporting*.xls" -Recurse | foreach {
$x = $_.LastWriteTime.ToShortDateString()
$new_folder_name = Get-Date $x -Format yyyy.MM.dd
$des_path = "c:usersusernamedocuments$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
}
}

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

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

$sourcePath = 'c:usersusernamedocumentsreporting'
$targetPath = 'c:usersusernamedocuments'
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开关用于测试。一旦您对 consoe 中显示的文本感到满意,请删除该开关以实际开始移动文件。

最新更新