将文件上移一个文件夹级别 [英] Move files up one folder level

查看:152
本文介绍了将文件上移一个文件夹级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为四月报告"的文件夹,其中包含一个月中每一天的文件夹.然后,每个文件夹都包含另一个包含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 $filesGet-ChildItem *\*\*\*来枚举文件.

  • Get-ChildItem *\*\* enumerates the dayreport folders (that's why the folder removal works), not the files in them. You need Get-ChildItem $files or Get-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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆