查找子目录中的所有 xls 文件,并根据文件创建日期将它们移动到文件夹中
Fild all xls files in subdirectories and move them to a folder based on file creation date
我有一个包含子文件夹的文件夹,每个子文件夹都有许多 excel 电子表格。我试图让 powershell 搜索子目录,然后将所有具有相同创建日期的 xls 文件移动到该创建日期的新文件夹中。我很接近我想这是我的代码。发生的事情是它只查看 "reporting" 中的文件,而不查看 "reporting" 的子文件夹。
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
}
}
无需先在 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
开关用于测试。一旦您对控制台中显示的文本感到满意,请移除该开关以实际开始移动文件。
我有一个包含子文件夹的文件夹,每个子文件夹都有许多 excel 电子表格。我试图让 powershell 搜索子目录,然后将所有具有相同创建日期的 xls 文件移动到该创建日期的新文件夹中。我很接近我想这是我的代码。发生的事情是它只查看 "reporting" 中的文件,而不查看 "reporting" 的子文件夹。
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
}
}
无需先在 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
开关用于测试。一旦您对控制台中显示的文本感到满意,请移除该开关以实际开始移动文件。