
close
close
Upcoming FREE Conference on Identity Management and Privileged Access Management
Managing files and folders is a never ending task, where I frequently see a common question on how to delete empty folders. Actually deleting a folder is very easy in PowerShell. The real question is how do I identify empty folders?
Let’s take a look. First, we’ll assume you are searching for folders from a given root.
$root = "C:\Work"
Beginning with PowerShell 3.0, you can easily filter files or folders. This will get all of the root or top-level folders.
dir $root -Directory
Grabbing a list of top-level file folder. (Image Credit: Jeff Hicks)
dir $root –Directory –recurse | Select Fullname
Filtering for all directories in Windows PowerShell. (Image Credit: Jeff Hicks)
dir $root -Directory -recurse | where { $_.GetFiles()} | Select Fullname
Thus, these folders are not empty.
Testing if folders contain an item with GetFiles() in Windows PowerShell. (Image Credit: Jeff Hicks)
dir $root -Directory -recurse | where { -NOT $_.GetFiles()} | Select Fullname
Using the reverse logic from the previous example. (Image Credit: Jeff Hicks)
Demo4 doesn’t contain a file and is a subfolder, but Demo3 contains a file. (Image Credit: Jeff Hicks)
(get-item $root).getfiles.OverloadDefinitions
GetFiles() method in Windows PowerShell. (Image Credit: Jeff Hicks)
[enum]::GetValues([system.io.searchoption])
Using GetValues and its SearchOption in Windows PowerShell. (Image Credit: Jeff Hicks)
dir $root -Directory -recurse | where { $_.GetFiles("*","AllDirectories")} | Select Fullname
And sure enough, these are the folders that contain at least one file somewhere in the path.
Using GetFiles() to search for files recursively in Windows PowerShell. (Image Credit: Jeff Hicks)
dir $root -Directory -recurse | where {-NOT $_.GetFiles("*","AllDirectories")} | Select Fullname
Using a -NOT operator to find a true list of empty folders. (Image Credit: Jeff Hicks)
dir $root -Directory -recurse | where {-NOT $_.GetFiles("*","AllDirectories")} | dir
But all I get is the directory entry.
Directory entry in Windows PowerShell. (Image Credit: Jeff Hicks)
dir $root -Directory -recurse | where {-NOT $_.GetFiles("*","AllDirectories")} | del -recurse -whatif
Performing the operation ‘Remove Directory’ on the target directory. (Image Credit: Jeff Hicks)
invoke-command -scriptblock { dir c:\shared -Directory -recurse | where {-NOT $_.GetFiles("*","AllDirectories")} | Select Fullname} -ComputerName CHI-FP02
I’m using the same command except it is running in a remote session on CHI-FP02.
Demonstrating how to run the operation on a remote computer. (Image Credit: Jeff Hicks)
invoke-command -scriptblock { dir c:\shared -Directory -recurse | where {-NOT $_.GetFiles("*","AllDirectories")} | del -recurse -whatif } -ComputerName CHI-FP02
Deleting the file folders in Windows PowerShell. (Image Credit: Jeff Hicks)
More in PowerShell
Most popular on petri