Home > Net >  Powershell: Move Subfolders but Ignore Files in Root?
Powershell: Move Subfolders but Ignore Files in Root?

Time:12-12

Got what I thought was a fairly straightforward question but after several hours of Googling I can't find an answer. Pretty sure Powershell is versatile enough to do this, I'm just not sure how to go code it up.

So basically, I have this:

  • W:\ (root)
  • Main Folder 1
    • Subfolder 1
      • Sub-Subfolder 1
      • Sub-Subfolder 2
      • Sub-Subfolder 3
      • File1.fil
      • File2.fil
      • File3.fil

All I'm trying to do is get Powershell to search Subfolder 1 and move Sub-Subfolders 1-3 (and their contents) into Subfolder 1, but ignore Files 1-3.

The syntax that I've worked up looks like this:

$source = "W:\Main Folder 1\Subfolder 1\"
$destination = "W:\Main Folder\"

Get-ChildItem $source -attributes D -Recurse | Move-Item -Destination "$destination" -Force -Verbose

When I -WhatIf it it looks like it should work, but then when I try it I get the dreaded "cannot create a file when that file already exists" (basically it's saying that it can't create folders in Main Folder 1 with the same names as ones from Subfolder 1). I've got a -Force flag there and I'd have thought this would do the trick, but...here we are.

Any idea what to do to force it to move them? (I don't want it to delete the existing folder to move the new one though.)

CodePudding user response:

If I understand what you're trying to do this code works.

$source = "G:\Test\A\FolderTwo"
$destination = "G:\Test\A"

Get-ChildItem -Path $source -Directory | 
    Move-Item -Destination $destination -Force -Verbose

Verbose Output:

VERBOSE: Performing the operation "Move Directory" on target "Item: G:\Test\A\FolderTwo\Folder2A Destination: G:\Test\A\Folder2A".
VERBOSE: Performing the operation "Move Directory" on target "Item: G:\Test\A\FolderTwo\Folder2B Destination: G:\Test\A\Folder2B".

The 7 regular files in the Source Folder remained there. The Directories in the Source Folder and all their contents including Sub folders were moved.

Just make sure you have the Source & Destination directories defined correctly. Note there is no need for the -Recurse switch as moving whole directories also moves their contents.

Edited to remove un-necessary quotes per mklelement0's comment below!

CodePudding user response:

This should get you further. Change the "$($folder.name)-2" to whatever you want to append the new folder names with.

$destination = "W:\Main Folder\"
$source = Get-ChildItem "W:\Main Folder 1\Subfolder 1\" -Directory

foreach ($folder in $source) {
    $folder | Move-Item -Destination $destination\"$($folder.name)-2"
}
  • Related