I’m on a Windows 11 machine, and I need a PowerShell command/script to do it.
I have a root folder with the following structure:
Root
Folder A
Packaging Folder A
Folder A1
1.png
2.png
Folder A2
1.png
2.png
Folder A1.zip
Folder A2.zip
Folder B
Packaging Folder B
Folder B1
1.png
2.png
Folder B2
1.png
2.png
Folder B1.zip
Folder B2.zip
Folder C
Folder D
...
I want a script to move the folders and files in the Packaging folders directly under its parent folder without flattening them. In other words, the resulted folder structure should look like this:
Root
Folder A
Packaging Folder A
Folder A1
1.png
2.png
Folder A2
1.png
2.png
Folder A1.zip
Folder A2.zip
Folder B
Packaging Folder B
Folder B1
1.png
2.png
Folder B2
1.png
2.png
Folder B1.zip
Folder B2.zip
Folder C
Folder D
...
Note that the .png files in Folder A1, A2, B1, B2, etc should NOT be moved under Folder A, B, etc (what I mean by “flattening them”).
I tried the following code to solve the problem:
$Root = "I:root"
Get-ChildItem -LiteralPath $Root -Directory | ForEach-Object {
$ParentFolder = $_
Get-ChildItem -LiteralPath $ParentFolder.FullName -Directory | ForEach-Object {
$SubSubFolder = $_
# Move all files and folders inside the sub-subfolder up to the parent folder
Get-ChildItem -LiteralPath $SubSubFolder.FullName | Move-Item -Destination $ParentFolder.FullName
# Optional: Remove the now-empty sub-subfolder
Remove-Item -LiteralPath $SubSubFolder.FullName
}
}
The problem with the code above is that it flattens the Folder A1, A2, B1, B2, etc (i.e. move the png files directly under Folder A, B, etc).
The code above also reports the following error “Move-Item : Cannot create a file when that file already exists.” The cause of the error is that, Folder A1 and A2 contains png files with same names, so they can’t be flattened under the same directory (Folder A).
I would greatly appreciate if someone can help with the flattening issue.