Moving a Nested "Packaging" Folder's Contents Up One Level in PowerShell Without Flattening

Abstract: When reorganizing folders, moving a wrapper folder's children up one level can accidentally flatten deeper subfolders if you enumerate the wrong level. This article explains the correct PowerShell approach and how to avo...

Created: 2026-11-12 by

The fix is to target the "Packaging" folders directly and move only their immediate children up one level — never enumerate the contents of the subfolders inside them. If you loop over every child directory and move its contents, you end up pushing files two levels up, which flattens your structure and causes "file already exists" errors when sibling folders contain identically named files.

Why the naive script flattens everything

A common first attempt looks like this:

$Root = "I:\root"

Get-ChildItem -LiteralPath $Root -Directory | ForEach-Object {
    $ParentFolder = $_
    Get-ChildItem -LiteralPath $ParentFolder.FullName -Directory | ForEach-Object {
        $SubSubFolder = $_
        Get-ChildItem -LiteralPath $SubSubFolder.FullName | Move-Item -Destination $ParentFolder.FullName
        Remove-Item -LiteralPath $SubSubFolder.FullName
    }
}

This fails for two reasons:

  • Wrong level of enumeration. The inner loop grabs every directory under Folder A — including Folder A1 and Folder A2 — and moves their contents (the PNG files) straight into Folder A. That is exactly the flattening you want to avoid. Only the children of the Packaging folder should move up one level; the subfolders themselves must move as whole units.
  • Name collisions. Because Folder A1 and Folder A2 both contain files named 1.png and 2.png, moving those files into the same destination produces Move-Item : Cannot create a file when that file already exists. This error is a symptom of the flattening, not a separate problem.

The correct approach

Instead of walking the tree level by level, filter for the folders whose name matches your packaging pattern (here, Packaging*) and move each of their immediate children up into the Packaging folder's parent. Because you move entire directories like Folder A1 as single items, their internal contents — including duplicate file names across siblings — travel untouched.

$Root = 'I:\root'

foreach ($parent in @(Get-ChildItem -LiteralPath $Root -Directory)) {
    foreach ($pkg in @(Get-ChildItem -LiteralPath $parent.FullName -Directory -Filter 'Packaging*')) {
        foreach ($item in @(Get-ChildItem -LiteralPath $pkg.FullName)) {
            $dest = Join-Path $parent.FullName $item.Name
            if (Test-Path -LiteralPath $dest) {
                Write-Warning "Skipped, already exists: $dest"
            } else {
                Move-Item -LiteralPath $item.FullName -Destination $dest
            }
        }
        # Optional: delete the Packaging folder once it's empty
        # if (-not (Get-ChildItem -LiteralPath $pkg.FullName -Force)) { Remove-Item -LiteralPath $pkg.FullName }
    }
}

Key details in this script:

  • Explicit destination with a collision check. Rather than piping into Move-Item and letting it fail, the script builds the destination path with Join-Path and tests it first. If something already exists there, it warns and skips instead of aborting or overwriting.
  • Wrapping the Get-ChildItem results in @(...) snapshots each listing before you start moving things. This prevents the pipeline from re-reading a directory that is being modified mid-loop.
  • -LiteralPath everywhere. Folder names containing brackets, square brackets, or other wildcard characters are handled safely.
  • Optional cleanup. The commented-out Remove-Item block deletes the empty Packaging folder only after verifying it is truly empty, using -Force to catch hidden files.

A shorter alternative using wildcards

If your folder names are consistent, Get-ChildItem accepts wildcards in the path itself, so you can locate all Packaging folders in one call:

$root = 'I:\Root'
Get-ChildItem "$($root)\*\Packaging*" -Directory | ForEach-Object {
    Get-ChildItem -LiteralPath $_.FullName | Move-Item -Destination $_.Parent.FullName -Verbose
    # Remove-Item -LiteralPath $_.FullName -Verbose   # optional cleanup
}

Here $_.Parent.FullName is the folder that contains the Packaging folder — exactly where the contents belong. The -Verbose switch prints every move so you can audit what happened. The trade-off versus the longer script: this version is more concise but has no per-item collision check, so it will stop with an error if a destination name already exists. Use the longer script if your data might contain conflicts.

Test before you commit

Batch moves are hard to undo, so protect yourself:

  1. Dry run first. Replace the Move-Item line with Write-Host "Would move $($item.FullName) -> $dest" and review the output.
  2. Back up the tree. A quick Copy-Item -Recurse of the root to a temp location gives you a rollback path.
  3. Verify with tree. Run tree /F from a command prompt before and after to confirm the structure changed the way you intended.

Frequently Asked Questions

Why did my script move the PNG files up instead of the folders?

Because you enumerated the directories inside the parent (which includes Folder A1, Folder A2, etc.) and moved their contents. You should enumerate the contents of the Packaging folder instead — those contents are the subfolders and zip files, and moving them as whole items preserves their internal structure.

How do I match a different folder name pattern?

Change the filter. In the long script, adjust -Filter 'Packaging*'; in the short one, adjust the wildcard path, e.g. "$root\*\*Pack*". The -Filter parameter matches against the folder name only.

What if a file with the same name already exists in the destination?

The longer script detects this with Test-Path and skips the item with a warning, leaving the original in place. If you want automatic renaming instead of skipping, you would need to generate a unique name (for example, appending a counter) before calling Move-Item.

Is it safe to delete the Packaging folder afterwards?

Only after confirming it is empty. Check with Get-ChildItem -LiteralPath $pkg.FullName -Force — the -Force flag reveals hidden and system files that a plain listing would miss. If the listing is empty, Remove-Item is safe.

Why use -LiteralPath instead of the default -Path?

The default -Path interprets [ and ] as wildcard characters, so folder names like Folder [2024] can silently match nothing or the wrong item. -LiteralPath treats the name exactly as written.

Does this work on Windows PowerShell 5.1 as well as PowerShell 7?

Yes. All the cmdlets used — Get-ChildItem, Move-Item, Join-Path, Test-Path, Remove-Item — behave the same in both versions for this scenario.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More