0

So i'm currently trying to delete a bunch of subfolders that were created by a program, on a recurring basis because it will recreate the subfolders. I know how to schedule the batch file, right now my issue is how to efficiently create the batch file to begin with. To clarify, say i have a directory named D:\IGSG. There are 250 folders within D:\IGSG, and within each one of those is a folder named D:\IGSG\F252341\arg. I want to delete all of the \arg folders, from all ~250 F folders I have, without deleting the other files inside the F folders. Right now the only way to do it that I know of would be to have a batch that goes

cd D:\IGSG\F252341 del /Q arg

and to repeat those lines for every subfolder, but typing out those folder names for every folder in there would be tedious, especially considering new ones are created from time to time. So i'm looking for a way with a batch to delete the subfolder of a subfolder, without deleting other files, if that makes sense.

  • 1
    There is similar question that was answered. https://stackoverflow.com/questions/12748786/delete-files-or-folder-recursively-on-windows-cmd – imbbTG Jun 30 '18 at 05:12

2 Answers2

1

This PowerShell script will recurse through the subdirectory structure and delete all files and subdirectories inside arg directories. Be sure to change the location of the IGSG directory to yours. When you are satisfied that the correct files will be deleted, remove the -WhatIf from the Remove-Item cmdlet.

Get-ChildItem -Directory -Recurse -Path 'C:\src\t\delsubs\IGSG\F*' -Filter 'arg' |
    Remove-Item -Path {(Join-Path -Path $_.FullName -ChildPath '*')} -Recurse -Force -WhatIf

If you need to run it from a cmd.exe shell, put the code above into a file named 'dodel.ps1' and run using:

powershell -NoProfile -File .\dodel.ps1
lit
  • 14,456
  • 10
  • 65
  • 119
  • As Remove-Item accepts piped input, the ForEach can be avoided, you just have to put the -Path paramter in a {script block}. One of the rare cases where batch/cmd line can compete –  Jul 01 '18 at 18:42
  • @LotPings - I appreciate your suggestion. I have tried several things, but not gotten it yet. How are you suggesting the `Remove-Item` line be written? – lit Jul 01 '18 at 19:15
  • `Remove-Item -Path {(Join-Path -Path $_.FullName -ChildPath '*')} -Recurse -Force -WhatIf` and remove the `ForEach-Object {}` it worked when I tried mine batch vs your ps1. –  Jul 01 '18 at 19:18
  • 1
    @LotPings - Great suggestion. It is going in now. – lit Jul 01 '18 at 19:27
1

On the cmd line for /d /r X:\path in combination with a wildcard will enumerate all folders names arg the appended .? meets this requirement:

for /d /r D:\IGSG %A in (arg.?) do @echo rd /s /q "%A" 

if the output looks right remove the echo.

In a batch file double the %-signs -> %%A

@Echo off
for /d /r D:\IGSG %%A in (arg.?) do echo rd /s /q "%%A"

One of the rare cases where batch/cmd line can compete with PowerShell.