Batch Command To Delete Only Empty Subfolders


WyattCollins

Member
Local time
10:22 PM
Posts
21
OS
Windows 11 Home 64-bit ver=22H2 build=22621.1702
Is there a cmd.exe batch command "one-liner" that deletes or removes only empty subdirectories?
 

My Computer

System One

  • OS
    Windows 11 Home 64-bit ver=22H2 build=22621.1702
    Computer type
    Laptop
    Manufacturer/Model
    HP 15-ef1105nr
    CPU
    AMD Athlon™ Silver 3050U
    Motherboard
    HP 8706 99.43 AMD Ryzen SOC rev. 00/FCH rev. 51 PCI-Express 3.0 (8.0 GT/s)
    Memory
    4 GB DDR4-2400 MHz RAM (1 x 4 GB)
    Graphics Card(s)
    HP AMD Radeon™ Graphics 400MHz GFX core
    Sound Card
    AMD/Realtek HD Audio Device
    Monitor(s) Displays
    15.6" HD LED (220 nits)
    Screen Resolution
    1366 x 768
    Hard Drives
    128 GB SATA 3 TLC M.2 SSD
    PSU
    45 W Smart AC power adapter; 3-cell, 41 Wh Li-ion
    Keyboard
    HPQ Standard PS/2
    Mouse
    ELAN touchpad; Logitech Wireless
    Internet Speed
    2.4 GHz/144 Mbps Realtek RTL8822CE 802.11ac PCIe Adapter
    Browser
    Google Chrome Version 115.0.5790.171 (Official Build) (64-bit)
    Antivirus
    McAfee LiveSafe™ (may get replaced with something more efficient)
    Other Info
    No optical drive; DirectX 12; HP True Vision 720p HD Webcam; BIOS: AMD AGESA PicassoPI-FP5 1.0.0.E UEFI; CCleaner; Glary Utilities; Speccy; CPU-Z; GPU-Z
Is there a cmd.exe batch command "one-liner" that deletes or removes only empty subdirectories?
Code:
for /f "delims=" %d in ('dir /s /b /ad ^| sort /r') do rd "%d"
(enter)

This will not work with directories with attributes set such as H,R and others.
If you want to document the progress, it can be piped to a file by adding either | d:\dellist.txt or > d:\dellist.txt .
 
Last edited:

My Computers

System One System Two

  • OS
    Windows 11 Pro for Workstations
    Computer type
    Laptop
    Manufacturer/Model
    ASUSTeK COMPUTER INC. TUF Gaming FX705GM
    CPU
    2.20 gigahertz Intel i7-8750H Hyper-threaded 12 cores
    Motherboard
    ASUSTeK COMPUTER INC. FX705GM 1.0
    Memory
    24428 Megabytes
    Graphics Card(s)
    Intel(R) UHD Graphics 630 / NVIDIA GeForce GTX 1060
    Sound Card
    Intel(R) Display Audio / Realtek(R) Audio
    Monitor(s) Displays
    Integrated Monitor (17.3"vis)
    Screen Resolution
    FHD 1920X1080 16:9
    Hard Drives
    2 SSD SATA/NVM Express 1.3
    WDS500G2B0A-00SM50 500.1 GB
    WDCSDAPNUW-1002 256 GB
    PSU
    19V DC 6.32 A 120 W
    Cooling
    Dual Fans
    Mouse
    MS Bluetooth
    Internet Speed
    Fiber 1GB Cox -us & 400MB Orange-fr
    Browser
    Edge Canary- Firefox Nightly-Chrome Dev
    Antivirus
    Windows Defender
    Other Info
    VMs of Windows 11 stable/Beta/Dev/Canary
    VM of XeroLinux- Arch based & Debian 12
  • Operating System
    Windows 11 Insider Canary
    Computer type
    Laptop
    Manufacturer/Model
    ASUS X751BP
    CPU
    AMD Dual Core A6-9220
    Motherboard
    ASUS
    Memory
    8 GB
    Graphics card(s)
    AMD Radeon R5 M420
    Sound Card
    Realtek
    Monitor(s) Displays
    17.3
    Screen Resolution
    1600X900 16:9
    Hard Drives
    1TB 5400RPM
Someone like @garlin might want to check this first. But it’s a batch file not a command.

Batch:
@echo off
set "mainFolder=C:\Path\To\Your\MainFolder"

for /f "delims=" %%d in ('dir "%mainFolder%" /ad /b /s ^| sort /r') do (
    rd "%%d" 2>nul
)

echo All empty subfolders in %mainFolder% have been deleted.pause

  • Replace C:\Path\To\Your\MainFolder with the path to your main folder.
  • Save the script as a .bat file, for example, DeleteEmptySubfolders.bat.
  • Run the batch file.
 

My Computers

System One System Two

  • OS
    Windows 11 Pro 23H2 Build 22631.4249
    Computer type
    PC/Desktop
    Manufacturer/Model
    Sin-built
    CPU
    Intel(R) Core(TM) i7-4770K CPU @ 3.50GHz (4th Gen?)
    Motherboard
    ASUS ROG Maximus VI Formula
    Memory
    32.0 GB of I forget and the box is in storage.
    Graphics Card(s)
    Gigabyte nVidia GeForce GTX 1660 Super OC 6GB
    Sound Card
    Onboard
    Monitor(s) Displays
    4 x LG 23MP75 - 2 x 24MK430H-B - 1 x Wacom Pro 22" Tablet
    Screen Resolution
    All over the place
    Hard Drives
    Too many to list.
    OS on Samsung 1TB 870 QVO SATA
    PSU
    Silverstone 1500
    Case
    NZXT Phantom 820 Full-Tower Case
    Cooling
    Noctua NH-D15 Elite Class Dual Tower CPU Cooler / 6 x EziDIY 120mm / 2 x Corsair 140mm somethings / 1 x 140mm Thermaltake something / 2 x 200mm Corsair.
    Keyboard
    Corsair K95 / Logitech diNovo Edge Wireless
    Mouse
    Logitech G402 / G502 / Mx Masters / MX Air Cordless
    Internet Speed
    100/40Mbps
    Browser
    All sorts
    Antivirus
    Kaspersky Premium
    Other Info
    I’m on a horse.
  • Operating System
    Windows 11 Pro 23H2 Build: 22631.4249
    Computer type
    Laptop
    Manufacturer/Model
    LENOVO Yoga 7i EVO OLED 14" Touchscreen i5 12 Core 16GB/512GB
    CPU
    Intel Core 12th Gen i5-1240P Processor (1.7 - 4.4GHz)
    Memory
    16GB LPDDR5 RAM
    Graphics card(s)
    Intel Iris Xe Graphics Processor
    Sound Card
    Optimized with Dolby Atmos®
    Screen Resolution
    QHD 2880 x 1800 OLED
    Hard Drives
    M.2 512GB
    Other Info
    …still on a horse.
Powershell:
$mainFolder = "C:\Path\To\Your\MainFolder"

Get-ChildItem -Path $mainFolder -Recurse -Directory | Where-Object { $_.GetFileSystemInfos().Count -eq 0 } | Remove-Item -Force

  • Replace C:\Path\To\Your\MainFolder with the path to your main folder.
  • Open PowerShell and run the command.
 

My Computers

System One System Two

  • OS
    Windows 11 Pro 23H2 Build 22631.4249
    Computer type
    PC/Desktop
    Manufacturer/Model
    Sin-built
    CPU
    Intel(R) Core(TM) i7-4770K CPU @ 3.50GHz (4th Gen?)
    Motherboard
    ASUS ROG Maximus VI Formula
    Memory
    32.0 GB of I forget and the box is in storage.
    Graphics Card(s)
    Gigabyte nVidia GeForce GTX 1660 Super OC 6GB
    Sound Card
    Onboard
    Monitor(s) Displays
    4 x LG 23MP75 - 2 x 24MK430H-B - 1 x Wacom Pro 22" Tablet
    Screen Resolution
    All over the place
    Hard Drives
    Too many to list.
    OS on Samsung 1TB 870 QVO SATA
    PSU
    Silverstone 1500
    Case
    NZXT Phantom 820 Full-Tower Case
    Cooling
    Noctua NH-D15 Elite Class Dual Tower CPU Cooler / 6 x EziDIY 120mm / 2 x Corsair 140mm somethings / 1 x 140mm Thermaltake something / 2 x 200mm Corsair.
    Keyboard
    Corsair K95 / Logitech diNovo Edge Wireless
    Mouse
    Logitech G402 / G502 / Mx Masters / MX Air Cordless
    Internet Speed
    100/40Mbps
    Browser
    All sorts
    Antivirus
    Kaspersky Premium
    Other Info
    I’m on a horse.
  • Operating System
    Windows 11 Pro 23H2 Build: 22631.4249
    Computer type
    Laptop
    Manufacturer/Model
    LENOVO Yoga 7i EVO OLED 14" Touchscreen i5 12 Core 16GB/512GB
    CPU
    Intel Core 12th Gen i5-1240P Processor (1.7 - 4.4GHz)
    Memory
    16GB LPDDR5 RAM
    Graphics card(s)
    Intel Iris Xe Graphics Processor
    Sound Card
    Optimized with Dolby Atmos®
    Screen Resolution
    QHD 2880 x 1800 OLED
    Hard Drives
    M.2 512GB
    Other Info
    …still on a horse.
You can ask ChatGPT to write it for you. For example, ChatGPT wrote the following script with the prompt "Write a PowerShell one-liner to recursively delete empty folders":

Powershell:
Get-ChildItem -Path "C:\Your\Target\Directory" -Recurse -Directory | Where-Object { $_.GetFiles().Count -eq 0 -and $_.GetDirectories().Count -eq 0 } | Remove-Item
 

My Computer

System One

  • OS
    Windows 10/11
    Computer type
    Laptop
    Manufacturer/Model
    Acer
This morning, I did work on a removal script based a Super User discussion thread, mostly because it's useful watching other devs argue about what's wrong with another person's script. The weird thing is if you have a top level folder that's empty, none of the Get-ChildItem -Recurse scripts will remove the starting folder. Because a parent folder isn't a child of itself. So I corrected that silly error.

Copy this script as Remove_EmptyFolders.bat:
Code:
<# : batch script
@echo off
powershell -nop Invoke-Expression ('$args = @(''%*'' -split '' '')' + [System.IO.File]::ReadAllText('%~f0'))
goto :eof
#>

if ($args[0] -eq '') {
   exit
}

$Path = $args[0]

if (-not (Test-Path $Path)) {
   "`"$Path`" folder doesn't exist."
   exit
}

@(Get-ChildItem $Path -Recurse -Directory -Force; Get-Item $Path) | Sort-Object -Property FullName -Descending | Where-Object { $($_ | Get-ChildItem -Force | Select-Object -First 1).Count -eq 0 } | Remove-Item -Force -Verbose

If you don't want the output, remove the "-Verbose" option from the script's final line. But I think it's useful to visually confirm what the script is doing.
Using the "-Recurse -Force" option, it will track down hidden folders for you.
Code:
C:\Users\GARLIN\Downloads>Remove_EmptyFolders.bat TEST
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\8".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\7".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\5\6".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\5".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\1\2\3\4".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\1\2\3".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\1\2".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\1".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST".
 

My Computer

System One

  • OS
    Windows 7
You can ask ChatGPT to write it for you. For example, ChatGPT wrote the following script with the prompt "Write a PowerShell one-liner to recursively delete empty folders":

Powershell:
Get-ChildItem -Path "C:\Your\Target\Directory" -Recurse -Directory | Where-Object { $_.GetFiles().Count -eq 0 -and $_.GetDirectories().Count -eq 0 } | Remove-Item
ChatGPT doesn't understand head vs. tail recursion. I'm sure your Programming 101 lecturer isn't giving it a passing grade...
 

My Computer

System One

  • OS
    Windows 7
This morning, I did work on a removal script based a Super User discussion thread, mostly because it's useful watching other devs argue about what's wrong with another person's script. The weird thing is if you have a top level folder that's empty, none of the Get-ChildItem -Recurse scripts will remove the starting folder. Because a parent folder isn't a child of itself. So I corrected that silly error.

Copy this script as Remove_EmptyFolders.bat:
Code:
<# : batch script
@echo off
powershell -nop Invoke-Expression ('$args = @(''%*'' -split '' '')' + [System.IO.File]::ReadAllText('%~f0'))
goto :eof
#>

if ($args[0] -eq '') {
   exit
}

$Path = $args[0]

if (-not (Test-Path $Path)) {
   "`"$Path`" folder doesn't exist."
   exit
}

@(Get-ChildItem $Path -Recurse -Directory -Force; Get-Item $Path) | Sort-Object -Property FullName -Descending | Where-Object { $($_ | Get-ChildItem -Force | Select-Object -First 1).Count -eq 0 } | Remove-Item -Force -Verbose

If you don't want the output, remove the "-Verbose" option from the script's final line. But I think it's useful to visually confirm what the script is doing.
Using the "-Recurse -Force" option, it will track down hidden folders for you.
Code:
C:\Users\GARLIN\Downloads>Remove_EmptyFolders.bat TEST
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\8".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\7".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\5\6".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\5".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\1\2\3\4".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\1\2\3".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\1\2".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST\1".
VERBOSE: Performing the operation "Remove Directory" on target "C:\Users\GARLIN\Downloads\TEST".
Am I required to use PowerShell to accomplish the desired result?
In my original post, I thought I made it clear enough by saying "cmd.exe"
 

My Computer

System One

  • OS
    Windows 11 Home 64-bit ver=22H2 build=22621.1702
    Computer type
    Laptop
    Manufacturer/Model
    HP 15-ef1105nr
    CPU
    AMD Athlon™ Silver 3050U
    Motherboard
    HP 8706 99.43 AMD Ryzen SOC rev. 00/FCH rev. 51 PCI-Express 3.0 (8.0 GT/s)
    Memory
    4 GB DDR4-2400 MHz RAM (1 x 4 GB)
    Graphics Card(s)
    HP AMD Radeon™ Graphics 400MHz GFX core
    Sound Card
    AMD/Realtek HD Audio Device
    Monitor(s) Displays
    15.6" HD LED (220 nits)
    Screen Resolution
    1366 x 768
    Hard Drives
    128 GB SATA 3 TLC M.2 SSD
    PSU
    45 W Smart AC power adapter; 3-cell, 41 Wh Li-ion
    Keyboard
    HPQ Standard PS/2
    Mouse
    ELAN touchpad; Logitech Wireless
    Internet Speed
    2.4 GHz/144 Mbps Realtek RTL8822CE 802.11ac PCIe Adapter
    Browser
    Google Chrome Version 115.0.5790.171 (Official Build) (64-bit)
    Antivirus
    McAfee LiveSafe™ (may get replaced with something more efficient)
    Other Info
    No optical drive; DirectX 12; HP True Vision 720p HD Webcam; BIOS: AMD AGESA PicassoPI-FP5 1.0.0.E UEFI; CCleaner; Glary Utilities; Speccy; CPU-Z; GPU-Z
Am I required to use PowerShell to accomplish the desired result?
In my original post, I thought I made it clear enough by saying "cmd.exe"

You could have asked ChatGPT in the first place...
Code:
@echo off
setlocal enabledelayedexpansion

:: Change this to the directory you want to clean up
set "targetDir=C:\path\to\your\directory"

:: Check if targetDir exists
if not exist "%targetDir%" (
    echo The specified directory does not exist.
    exit /b 1
)

:: Go to the target directory
pushd "%targetDir%"

:: Loop to find and remove empty directories
:loop
set "removed=0"
for /f "delims=" %%d in ('dir /ad /b /s ^| sort /r') do (
    if not exist "%%d\*" (
        rd "%%d" 2>nul
        if not exist "%%d" (
            echo Removed empty directory: %%d
            set "removed=1"
        )
    )
)

:: If no directories were removed, exit the loop
if "!removed!"=="0" goto :done

:: Repeat the loop if any directories were removed
goto :loop

:done
:: Return to the original directory
popd
echo Cleanup complete.
endlocal
 

My Computer

System One

  • OS
    Windows 7
MUCH easier way to do this:

robocopy "C:\Source" "C:\Source" /S /move

This command effectively moves the files over the top of themselves while deleting empty folders.

CAUTION: I would test this on a test folder first. I gave it a very small test and it seems to work, but test yourself to be sure.
 

My Computers

System One System Two

  • OS
    Win11 Pro 24H2
    Computer type
    PC/Desktop
    Manufacturer/Model
    Self-built
    CPU
    Intel i7 11700K
    Motherboard
    ASUS Prime Z590-A MB
    Memory
    64GB (Waiting for warranty replacement of another 64GB for 128GB total)
    Graphics Card(s)
    No GPU - Built-in Intel Graphics
    Sound Card
    Integrated
    Monitor(s) Displays
    HP Envy 32
    Screen Resolution
    2560 x 1440
    Hard Drives
    1 x 1TB NVMe SSD
    1 x 2TB NVMe SSD
    1 x 4TB NVMe SSD
    3 x 512GB 2.5" SSD
    1 x 4TB 2.5" SSD
    5 x 8TB Seagate Barracuda HDD
    PSU
    Corsair HX850i
    Case
    Corsair iCUE RGB 5000X mid tower case
    Cooling
    Noctua NF-S12A chromax.black.swap case fans (Qty. 7) & Home Computer Specifications, Configuration, and Usage Notes General Specifications ASUS Prime Z590-A motherboard, serial number M1M0KC222467ARP Intel Core i7-11700K CPU (11th Gen Rocket Lake / LGA 1200 Socket) 128GB Crucial Ballistix RGB DDR4 3200 MHz DRAM (4 x 32GB) Corsair iCUE RGB 5000X mid tower case Noctua NH-D15 chromax.black CPU cooler Noctua NF-S12A chromax.black.swap case fans (Qty. 7) & Corsair LL-120 RGB Fans (Qty. 3)
    Keyboard
    Corsair K70 Max RGB Magnetic Keyboard
    Mouse
    Logitech MX Master 3
    Internet Speed
    1Gb Up / 1 Gb Down
    Browser
    Edge
    Antivirus
    Windows Defender
    Other Info
    The five 8TB drives and three 512GB SSDs are part of a DrivePool using StableBit DrivePool software. The three SSDs are devoted purely to caching for the 8TB drives. All of the important data is stored in triplicate so that I can withstand simultaneous failure of 2 disks.

    Networking: 2.5Gbps Ethernet and WiFi 6e
  • Operating System
    Win11 Pro 23H2
    Computer type
    Laptop
    Manufacturer/Model
    Lenovo ThinkBook 13x Gen 2
    CPU
    Intel i7-1255U
    Memory
    16 GB
    Graphics card(s)
    Intel Iris Xe Graphics
    Sound Card
    Realtek® ALC3306-CG codec
    Monitor(s) Displays
    13.3-inch IPS Display
    Screen Resolution
    WQXGA (2560 x 1600)
    Hard Drives
    2 TB 4 x 4 NVMe SSD
    PSU
    USB-C / Thunderbolt 4 Power / Charging
    Mouse
    Buttonless Glass Precision Touchpad
    Keyboard
    Backlit, spill resistant keyboard
    Internet Speed
    1Gb Up / 1Gb Down
    Browser
    Edge
    Antivirus
    Windows Defender
    Other Info
    WiFi 6e / Bluetooth 5.1 / Facial Recognition / Fingerprint Sensor / ToF (Time of Flight) Human Presence Sensor
Am I required to use PowerShell to accomplish the desired result?
In my original post, I thought I made it clear enough by saying "cmd.exe"
The script @garlin provided is implemented as PowerShell code in a batch file wrapper, so it will most certainly work from a cmd prompt.
 

My Computer

System One

  • OS
    Windows 10/11
    Computer type
    Laptop
    Manufacturer/Model
    Acer
You can ask ChatGPT to write it for you. For example, ChatGPT wrote the following script with the prompt "Write a PowerShell one-liner to recursively delete empty folders":

Powershell:
Get-ChildItem -Path "C:\Your\Target\Directory" -Recurse -Directory | Where-Object { $_.GetFiles().Count -eq 0 -and $_.GetDirectories().Count -eq 0 } | Remove-Item
Trust an Artificial Idiot at your peril!
 

My Computer

System One

  • OS
    Windows 11 Pro
    Computer type
    PC/Desktop
    Manufacturer/Model
    Self build
    CPU
    Core i7-13700K
    Motherboard
    Asus TUF Gaming Plus WiFi Z790
    Memory
    64 GB Kingston Fury Beast DDR5
    Graphics Card(s)
    Gigabyte GeForce RTX 2060 Super Gaming OC 8G
    Sound Card
    Realtek S1200A
    Monitor(s) Displays
    Viewsonic VP2770
    Screen Resolution
    2560 x 1440
    Hard Drives
    Kingston KC3000 2TB NVME SSD & SATA HDDs & SSD
    PSU
    EVGA SuperNova G2 850W
    Case
    Nanoxia Deep Silence 1
    Cooling
    Noctua NH-D14
    Keyboard
    Microsoft Digital Media Pro
    Mouse
    Logitech Wireless
    Internet Speed
    50 Mb / s
    Browser
    Chrome
    Antivirus
    Defender
Why does everyone seem to want to do this the hard way? :-)
 

My Computers

System One System Two

  • OS
    Win11 Pro 24H2
    Computer type
    PC/Desktop
    Manufacturer/Model
    Self-built
    CPU
    Intel i7 11700K
    Motherboard
    ASUS Prime Z590-A MB
    Memory
    64GB (Waiting for warranty replacement of another 64GB for 128GB total)
    Graphics Card(s)
    No GPU - Built-in Intel Graphics
    Sound Card
    Integrated
    Monitor(s) Displays
    HP Envy 32
    Screen Resolution
    2560 x 1440
    Hard Drives
    1 x 1TB NVMe SSD
    1 x 2TB NVMe SSD
    1 x 4TB NVMe SSD
    3 x 512GB 2.5" SSD
    1 x 4TB 2.5" SSD
    5 x 8TB Seagate Barracuda HDD
    PSU
    Corsair HX850i
    Case
    Corsair iCUE RGB 5000X mid tower case
    Cooling
    Noctua NF-S12A chromax.black.swap case fans (Qty. 7) & Home Computer Specifications, Configuration, and Usage Notes General Specifications ASUS Prime Z590-A motherboard, serial number M1M0KC222467ARP Intel Core i7-11700K CPU (11th Gen Rocket Lake / LGA 1200 Socket) 128GB Crucial Ballistix RGB DDR4 3200 MHz DRAM (4 x 32GB) Corsair iCUE RGB 5000X mid tower case Noctua NH-D15 chromax.black CPU cooler Noctua NF-S12A chromax.black.swap case fans (Qty. 7) & Corsair LL-120 RGB Fans (Qty. 3)
    Keyboard
    Corsair K70 Max RGB Magnetic Keyboard
    Mouse
    Logitech MX Master 3
    Internet Speed
    1Gb Up / 1 Gb Down
    Browser
    Edge
    Antivirus
    Windows Defender
    Other Info
    The five 8TB drives and three 512GB SSDs are part of a DrivePool using StableBit DrivePool software. The three SSDs are devoted purely to caching for the 8TB drives. All of the important data is stored in triplicate so that I can withstand simultaneous failure of 2 disks.

    Networking: 2.5Gbps Ethernet and WiFi 6e
  • Operating System
    Win11 Pro 23H2
    Computer type
    Laptop
    Manufacturer/Model
    Lenovo ThinkBook 13x Gen 2
    CPU
    Intel i7-1255U
    Memory
    16 GB
    Graphics card(s)
    Intel Iris Xe Graphics
    Sound Card
    Realtek® ALC3306-CG codec
    Monitor(s) Displays
    13.3-inch IPS Display
    Screen Resolution
    WQXGA (2560 x 1600)
    Hard Drives
    2 TB 4 x 4 NVMe SSD
    PSU
    USB-C / Thunderbolt 4 Power / Charging
    Mouse
    Buttonless Glass Precision Touchpad
    Keyboard
    Backlit, spill resistant keyboard
    Internet Speed
    1Gb Up / 1Gb Down
    Browser
    Edge
    Antivirus
    Windows Defender
    Other Info
    WiFi 6e / Bluetooth 5.1 / Facial Recognition / Fingerprint Sensor / ToF (Time of Flight) Human Presence Sensor
CMD will be around forever, or probably for another decade.

But if you learn PS, it is a better use of your programming time. I can do regular expressions and string handling in a concise manner, instead the arcane hoops CMD makes you jump through. No delayed expansion nonsense. Not to mention, MS has invested a huge amount of work to expose many Windows API features through native PS commands. So you don't need pipe 3-5 different external commands in a row to extract a single data value.
 

My Computer

System One

  • OS
    Windows 7
Why does everyone seem to want to do this the hard way? :-)
It looks like your recommendation of robocopy "C:\Source" "C:\Source" /S /move works well for recursively deleting completely empty folders.

However, it doesn't remove folders that only contain hidden/system files such as desktop.ini or thumbs.db, but that's also true of the other scripts that have been posted.

A folder that only contains a hidden/system desktop.ini file will show "0 items" in Explorer (with default settings), so it would be useful to have a script that removes such folders.
 

My Computer

System One

  • OS
    Windows 10/11
    Computer type
    Laptop
    Manufacturer/Model
    Acer
I'll have to think about this a bit, but a question first:

Is the goal to delete all empty folders AND folders that contain ONLY hidden OR system files? In other words, if there are any other files in those folders, do not delete them. Does that sound right? Just want to be 100% sure that if I am trying to figure this out I am actually trying to perform the correct operation.
 

My Computers

System One System Two

  • OS
    Win11 Pro 24H2
    Computer type
    PC/Desktop
    Manufacturer/Model
    Self-built
    CPU
    Intel i7 11700K
    Motherboard
    ASUS Prime Z590-A MB
    Memory
    64GB (Waiting for warranty replacement of another 64GB for 128GB total)
    Graphics Card(s)
    No GPU - Built-in Intel Graphics
    Sound Card
    Integrated
    Monitor(s) Displays
    HP Envy 32
    Screen Resolution
    2560 x 1440
    Hard Drives
    1 x 1TB NVMe SSD
    1 x 2TB NVMe SSD
    1 x 4TB NVMe SSD
    3 x 512GB 2.5" SSD
    1 x 4TB 2.5" SSD
    5 x 8TB Seagate Barracuda HDD
    PSU
    Corsair HX850i
    Case
    Corsair iCUE RGB 5000X mid tower case
    Cooling
    Noctua NF-S12A chromax.black.swap case fans (Qty. 7) & Home Computer Specifications, Configuration, and Usage Notes General Specifications ASUS Prime Z590-A motherboard, serial number M1M0KC222467ARP Intel Core i7-11700K CPU (11th Gen Rocket Lake / LGA 1200 Socket) 128GB Crucial Ballistix RGB DDR4 3200 MHz DRAM (4 x 32GB) Corsair iCUE RGB 5000X mid tower case Noctua NH-D15 chromax.black CPU cooler Noctua NF-S12A chromax.black.swap case fans (Qty. 7) & Corsair LL-120 RGB Fans (Qty. 3)
    Keyboard
    Corsair K70 Max RGB Magnetic Keyboard
    Mouse
    Logitech MX Master 3
    Internet Speed
    1Gb Up / 1 Gb Down
    Browser
    Edge
    Antivirus
    Windows Defender
    Other Info
    The five 8TB drives and three 512GB SSDs are part of a DrivePool using StableBit DrivePool software. The three SSDs are devoted purely to caching for the 8TB drives. All of the important data is stored in triplicate so that I can withstand simultaneous failure of 2 disks.

    Networking: 2.5Gbps Ethernet and WiFi 6e
  • Operating System
    Win11 Pro 23H2
    Computer type
    Laptop
    Manufacturer/Model
    Lenovo ThinkBook 13x Gen 2
    CPU
    Intel i7-1255U
    Memory
    16 GB
    Graphics card(s)
    Intel Iris Xe Graphics
    Sound Card
    Realtek® ALC3306-CG codec
    Monitor(s) Displays
    13.3-inch IPS Display
    Screen Resolution
    WQXGA (2560 x 1600)
    Hard Drives
    2 TB 4 x 4 NVMe SSD
    PSU
    USB-C / Thunderbolt 4 Power / Charging
    Mouse
    Buttonless Glass Precision Touchpad
    Keyboard
    Backlit, spill resistant keyboard
    Internet Speed
    1Gb Up / 1Gb Down
    Browser
    Edge
    Antivirus
    Windows Defender
    Other Info
    WiFi 6e / Bluetooth 5.1 / Facial Recognition / Fingerprint Sensor / ToF (Time of Flight) Human Presence Sensor
Follow-up: I asked co-pilot how to do this and it gave me the below powershell script. I want to stress that I have not tested this, but the claim is that this code will do what you are looking for. Test it on unimportant data first!

Powershell:
# Define the path to start the search
$path = "C:\Your\Directory\Path"

# Get all directories recursively
$directories = Get-ChildItem -Path $path -Recurse -Directory

foreach ($dir in $directories) {
    # Get all files and subdirectories, including hidden and system files
    $items = Get-ChildItem -Path $dir.FullName -Force

    # Check if the directory is empty or contains only hidden/system files
    if ($items.Count -eq 0 -or ($items | Where-Object { $_.Attributes -match "Hidden|System" }).Count -eq $items.Count) {
        Remove-Item -Path $dir.FullName -Recurse -Force
    }
}
 

My Computers

System One System Two

  • OS
    Win11 Pro 24H2
    Computer type
    PC/Desktop
    Manufacturer/Model
    Self-built
    CPU
    Intel i7 11700K
    Motherboard
    ASUS Prime Z590-A MB
    Memory
    64GB (Waiting for warranty replacement of another 64GB for 128GB total)
    Graphics Card(s)
    No GPU - Built-in Intel Graphics
    Sound Card
    Integrated
    Monitor(s) Displays
    HP Envy 32
    Screen Resolution
    2560 x 1440
    Hard Drives
    1 x 1TB NVMe SSD
    1 x 2TB NVMe SSD
    1 x 4TB NVMe SSD
    3 x 512GB 2.5" SSD
    1 x 4TB 2.5" SSD
    5 x 8TB Seagate Barracuda HDD
    PSU
    Corsair HX850i
    Case
    Corsair iCUE RGB 5000X mid tower case
    Cooling
    Noctua NF-S12A chromax.black.swap case fans (Qty. 7) & Home Computer Specifications, Configuration, and Usage Notes General Specifications ASUS Prime Z590-A motherboard, serial number M1M0KC222467ARP Intel Core i7-11700K CPU (11th Gen Rocket Lake / LGA 1200 Socket) 128GB Crucial Ballistix RGB DDR4 3200 MHz DRAM (4 x 32GB) Corsair iCUE RGB 5000X mid tower case Noctua NH-D15 chromax.black CPU cooler Noctua NF-S12A chromax.black.swap case fans (Qty. 7) & Corsair LL-120 RGB Fans (Qty. 3)
    Keyboard
    Corsair K70 Max RGB Magnetic Keyboard
    Mouse
    Logitech MX Master 3
    Internet Speed
    1Gb Up / 1 Gb Down
    Browser
    Edge
    Antivirus
    Windows Defender
    Other Info
    The five 8TB drives and three 512GB SSDs are part of a DrivePool using StableBit DrivePool software. The three SSDs are devoted purely to caching for the 8TB drives. All of the important data is stored in triplicate so that I can withstand simultaneous failure of 2 disks.

    Networking: 2.5Gbps Ethernet and WiFi 6e
  • Operating System
    Win11 Pro 23H2
    Computer type
    Laptop
    Manufacturer/Model
    Lenovo ThinkBook 13x Gen 2
    CPU
    Intel i7-1255U
    Memory
    16 GB
    Graphics card(s)
    Intel Iris Xe Graphics
    Sound Card
    Realtek® ALC3306-CG codec
    Monitor(s) Displays
    13.3-inch IPS Display
    Screen Resolution
    WQXGA (2560 x 1600)
    Hard Drives
    2 TB 4 x 4 NVMe SSD
    PSU
    USB-C / Thunderbolt 4 Power / Charging
    Mouse
    Buttonless Glass Precision Touchpad
    Keyboard
    Backlit, spill resistant keyboard
    Internet Speed
    1Gb Up / 1Gb Down
    Browser
    Edge
    Antivirus
    Windows Defender
    Other Info
    WiFi 6e / Bluetooth 5.1 / Facial Recognition / Fingerprint Sensor / ToF (Time of Flight) Human Presence Sensor
However, it doesn't remove folders that only contain hidden/system files such as desktop.ini or thumbs.db, but that's also true of the other scripts that have been posted.
The question becomes do you provide an exclusion list, like for Explorer files (desktop.ini, Thumbs.db) to ignore while counting? Because other hidden or system files may be essential to the folder's existence.
Say the user runs the script on the Windows folder.
 

My Computer

System One

  • OS
    Windows 7
The question becomes do you provide an exclusion list, like for Explorer files (desktop.ini, Thumbs.db) to ignore while counting? Because other hidden or system files may be essential to the folder's existence.
Say the user runs the script on the Windows folder.
Therein lies the challenge. I think, for safety, an exclusion (inclusion?) list is the correct way to do it.
 

My Computer

System One

  • OS
    Windows 10/11
    Computer type
    Laptop
    Manufacturer/Model
    Acer

Latest Support Threads

Back
Top Bottom