Aaron O Aaron O - 2 months ago 12
PowerShell Question

PowerShell Script to Delete Everything on a drive except hidden and select directories and anything below them

Okay so I am trying to keep a drive, specifically D, completely clear of anything on a server except for select directories and their children

This is what I have so far:

Get-ChildItem -Path "D:\" -Exclude "DirApple", "DirBanana", "Dir Cherry", "Script", "TEST" | foreach ($_) {
"CLEANING :" + $_.fullname
Remove-Item $_.fullname -Force -Recurse
"CLEANED... :" + $_.fullname

This works great if my path is D:\TEST\ (I replicated everything in D under D test including what I wanted removed), but if my path is D:\ it does not work at all


-Exclude for Get-ChildItem only excludes filenames, not directory names. For this reason try using Get-Item instead for this problem. When combined with a WildCard for the path, this will give you the desired result.

 Get-Item -Path "D:\*" -Exclude "DirApple", "DirBanana", "Dir Cherry", "Script", "TEST" | foreach ($_) {
       "CLEANING :" + $_.fullname
       Remove-Item $_.fullname -Force -Recurse
       "CLEANED... :" + $_.fullname

Why do I have to do this?

The -Exclude param for Get-ChildItem is meant to exclude only Files, not directories themselves, as seen in the help:

> help dir -Parameter Exclude

 -Exclude <String[]>
   Omits the specified items. The value of this parameter qualifies the Path parameter. 
   Enter a path element or pattern, such as "*.txt".

So we were really just using the wrong tool. If you look at the help for -Exclude for Get-Item, you'll note that:

 The Exclude parameter is effective only when the command includes the contents of an item 
 such as C:\Windows\*, where the wildcard character specifies the contents of the 
 C:\Windows directory.

This is why we had to add a WildCard to the Path.