Move files up one folder level

爱⌒轻易说出口 提交于 2019-11-28 02:17:38

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

Something like this should do it:

$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 $_
    }
}

Run the following script on April reports directory to move files up one level.

Get-ChildItem -Recurse -Filter "dayreports" | Get-ChildItem | Move-Item -Destination {$_.Directory.Parent.FullName}

The following line is to remove dayreports. Use it after you have already moved the files to parent folder. You can check if `dayreports' is empty. I skipped that part assuming you already moved the files.

Get-ChildItem -Recurse -Filter "dayreports" | Remove-Item -Recurse

To make it a one liner just-

Get-ChildItem -Recurse -Filter "dayreports" | Get-ChildItem | Move-Item -Destination {$_.Directory.Parent.FullName}; Get-ChildItem -Recurse -Filter "dayreports" | Remove-Item -Recurse
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!