Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

powershell - Move files up one folder level

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

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

The step to delete the extra folders "dayreports" works but the files have not been moved.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are 2 mistakes in your code:

  • 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 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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...