Home > Mobile >  Move Subfolder up one level including its contents
Move Subfolder up one level including its contents

Time:04-21

I need to move a lot of sub-folders. Each client has this structure and needs to be modified

The only folder I need to move is the "Correspondence" folders with all its contents. It needs to come "up" one level to the same level as the "2022" folder

The current folder structure looks like this:

Clients
........Surname,Initials
................................2022, Prior Years
.................................................................2018
.................................................................2019
.................................................................2020
.................................................................2021
.................................................................Calculations
.................................................................Correspondence

and this is what I need

Clients
===>Surname,Initials
===>2022, Correspondence, Prior Years
.......................................................................2018
.......................................................................2019
.......................................................................2020
.......................................................................2021
.......................................................................Calculations

This is what I have tried

dir -Directory | % {Push-Location $_.FullName; dir './Correspondence' | % {Move-Item $_.FullName} but that didn't work and resulted in errors

dir -Directory | % {Push-Location $_.FullName; dir './Correspondence' | % {Move-Item $_.FullName} That also resulted in errors

CodePudding user response:

The following locates all subdirectories named Correspondence in the current directory's subtree and moves them up one level:

(Get-ChildItem -Recurse -Directory -Filter 'Correspondence') |
  Move-Item -Destination { $_.Parent.Parent.FullName } -WhatIf

Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.

Note:

  • The Get-ChildItem call is enclosed in (...) so that all its output is collected up front, to rule out the possibility of the move operations interfering with the enumeration of the file-system items.

  • The -Destination argument is provided in the form of a delay-bind script block, which allows deriving the argument value from the input object at hand, reflected in the automatic $_ variable:

    • The .Parent property of the System.IO.DirectoryInfo instances output by Get-ChildItem reflects the parent directory (as an instance of the same type), i.e. the directory in which the subdirectory hand is currently located.

    • .Parent.Parent therefore reflects the parent directory of the one in which the subdirectory is currently located, and .FullName property contains its full path.

  • Related