将文件上移一个文件夹级别 [英] Move files up one folder level
问题描述
我有一个名为四月报告"的文件夹,其中包含一个月中每一天的文件夹.然后,每个文件夹都包含另一个包含PDF文件的文件夹:
I have a folder called "April reports" that contains a folder for each day of the month. Each folder then contains another folder which contains PDF files:
April reports
├─01-04-2018
│ └─dayreports
│ ├─approved.pdf
│ └─unapproved.pdf
│
├─02-04-2018
│ └─dayreports
│ ├─approved.pdf
│ └─unapproved.pdf
╎
╎
└─30-04-2018
└─dayreports
├─approved.pdf
└─unapproved.pdf
PDF每天都有相同的名称,因此我要做的第一件事是将它们上移一个级别,这样我就可以使用包含日期的文件夹名称来重命名每个文件,以便包含日期.我尝试过的脚本是这样的(在四月报告"中设置了路径):
The PDFs have the same name for each day so the first thing I want to do is move them up one level so that I can use the folder name containing the date to rename each file so that it will contain the date. The script I have tried is this (with the path set at "April Reports") :
$files = Get-ChildItem *\*\*
Get-ChildItem *\*\* | % {
Move-Item $_.FullName (($_.Parent).Parent).FullName
}
$files | Remove-Item -Recurse
删除多余文件夹"dayreports"的步骤有效,但是文件尚未移动.
The step to delete the extra folders "dayreports" works but the files have not been moved.
推荐答案
您的代码中有2个错误:
There are 2 mistakes in your code:
-
Get-ChildItem *\*\*
枚举dayreport
文件夹(这就是删除文件夹的原因),而不是其中的文件.您需要Get-ChildItem $files
或Get-ChildItem *\*\*\*
来枚举文件.
Get-ChildItem *\*\*
enumerates thedayreport
folders (that's why the folder removal works), not the files in them. You needGet-ChildItem $files
orGet-ChildItem *\*\*\*
to enumerate the files.
FileInfo
对象没有属性Parent
,只有DirectoryInfo
对象具有属性.将属性Directory
用于FileInfo
对象.此外,点访问通常可以通过菊花链方式进行,因此不需要所有的括号.
FileInfo
objects don't have a property Parent
, only DirectoryInfo
objects do. Use the property Directory
for FileInfo
objects. Also, dot-access can usually be daisy-chained, so all the parentheses aren't required.
这不是一个错误,但是很复杂:Move-Item
可以直接从管道读取,因此您无需将其放入循环中.
Not a mistake, but an over-complication: Move-Item
can read directly from the pipeline, so you don't need to put it in a loop.
将您的代码更改为类似的代码,它将完成您想要的操作:
Change your code to something like this, and it will do what you want:
$files = Get-ChildItem '*\*\*'
Get-ChildItem $files | Move-Item -Destination { $_.Directory.Parent.FullName }
$files | Remove-Item -Recurse
这篇关于将文件上移一个文件夹级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!