将文件上移一个文件夹级别



我有一个名为"April reports"的文件夹,其中包含一个月中每一天的文件夹。然后,每个文件夹都包含另一个包含PDF文件的文件夹:

April报告├─2018年4月1日│ └─日报表│   ├─批准.pdf│   └─不受欢迎.pdf│├─2018年4月2日│ └─日报表│   ├─批准.pdf│   └─不受欢迎.pdf╎╎└─2018年4月30日└─日报表├─批准.pdf└─未批准的.pdf

pdf每天都有相同的名称,所以我想做的第一件事是将它们上移一级,这样我就可以使用包含日期的文件夹名称重命名每个文件,使其包含日期。我尝试过的脚本是这样的(路径设置为"四月报告"(:

$files = Get-ChildItem ***
Get-ChildItem *** | % {
Move-Item $_.FullName (($_.Parent).Parent).FullName
}
$files | Remove-Item -Recurse

删除额外文件夹"dayreports"的步骤有效,但文件尚未移动。

您的代码中有两个错误:

  • Get-ChildItem ***枚举的是dayreport文件夹(这就是删除文件夹的原因(,而不是其中的文件。您需要Get-ChildItem $filesGet-ChildItem ****来枚举文件。

  • FileInfo对象没有属性Parent,只有DirectoryInfo对象有。请为FileInfo对象使用属性Directory。此外,点访问通常可以是菊花链的,因此不需要所有的括号。

这不是一个错误,而是一个过于复杂的问题:Move-Item可以直接从管道中读取,所以不需要将其放入循环中。

把你的代码改成这样,它会做你想做的事:

$files = Get-ChildItem '***'
Get-ChildItem $files | Move-Item -Destination { $_.Directory.Parent.FullName }
$files | Remove-Item -Recurse

应该这样做:

$rootPath = "<FULL-PATH-TO-YOUR-April reports-FOLDER>"
Get-ChildItem -Path $rootPath -Directory | ForEach-Object {
# $_ now contains the folder with the date like '01-04-2018'
# this is the folder where the .pdf files should go
$targetFolder = $_.FullName
Resolve-Path "$targetFolder*" | ForEach-Object {
# $_ here contains the fullname of the subfolder(s) within '01-04-2018'
Move-Item -Path "$_*.*" -Destination $targetFolder -Force
# delete the now empty 'dayreports' folder
Remove-Item -Path $_
}
}

最新更新