How to delete only the sub-folders and sub-folder contents but not individual files from the root of a folder using powershell

Viewed 31

A given folder "AppInstall" contains multiple unknown installation packages but the logs for those packages exist in the root of "AppInstall". I want to delete the folders and contents of "packages" without deleting the logs in the root of "AppInstall".

Example:

Before removal code

C:\AppInstall\Package1\AnotherFolder\something.txt
C:\AppInstall\Package1\a.txt
C:\AppInstall\Package1\b.txt
C:\AppInstall\Package1\c.txt
C:\AppInstall\Package2\a.txt
C:\AppInstall\Package2\b.txt
C:\AppInstall\Package1.log
C:\AppInstall\Package2.log

After removal code

C:\AppInstall\Package1.log
C:\AppInstall\Package2.log
1 Answers

You can retrieve the folders under your directory using the -Directory switch (v3+), then you can pipe that to Remove-Item utilizing -Recurse to delete everything and -Force to suppress being prompted:

Get-ChildItem -Path C:\AppInstall -Directory | Remove-Item -Recurse -Force
Related