Alessandro Schalk
Alessandro Schalk

Reputation: 3

Delete files from folder structure with exclude

currently I am trying to delete files inside a folder structure

root
|
|__subfolder1 (includes files)
|
|__subfolder2 (includes files)
|
etc

The script has to delete all files inside the subfolders except subfolder1 and not delete the subfolders. The thing I am not getting to work is to exclude the files inside of "subfolder1".

I am trying something like this

Get-ChildItem -Path E:\root -Include *.* -File -Recurse -Exclude E:\root\subfolder1 | foreach {$_.Delete()}

Upvotes: 0

Views: 411

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200523

Since the subfolder you want to exclude is always directly under the root folder I'd do the processing in 2 steps:

  • Enumerate the child folders of the root folder and exclude subfolder1.
  • Enumerate all files from the remaining folders and delete them.

Something like this:

$root     = 'root'
$excludes = 'subfolder1'

Get-ChildItem $root -Directory -Exclude $excludes | ForEach-Object {
    Get-ChildItem $_.FullName -File -Recurse -Force | Remove-Item -Force
}

Upvotes: 1

Related Questions