Find All Empty folder on my File Server

I have a drive with user folders and I am looking to delete all the folders that are empty on the file system (NTFS)

I tried this code

$SomePath=“j:\users”

Get-ChildItem -Path $SomePath -Recurse -Directory | ForEach-Object -Process {
if ($false -eq $.GetFileSystemInfos())
{
$
.FullName
}
}

I only need the top level folders that are empty not a sub folder within a sub folder that is empty

Many folders do not have any folders or files in them some folders have files and folders these I want to exclude. If they have a folder that is empty I do not care at this point about those empty folders Only the top level

Example

 

J:\Users
UserA
FolderA
Files
UserB
UserC
UserD
FolderA Empty
FolderB
Files

I the above example I would like only UserB and UserC

Any ideas

 

Thank you

Tom

 

 

 

Please read how to format code/errors as it makes it difficult or even undesirable to help you.

You were close, just use a where clause

$SomePath=”j:\users”

Get-ChildItem -Path $somepath -Recurse -Directory |
    Where-Object {!($_.getfilesysteminfos())} | Select-Object fullname

You will end up with an object that has a fullname property. If you want to just get the fullnames, add -ExpandProperty to the select statement.

$SomePath=”j:\users”

Get-ChildItem -Path $somepath -Recurse -Directory |
    Where-Object {!($_.getfilesysteminfos())} |
        Select-Object -ExpandProperty fullname

Doug

 

Thanks for the help

 

I ran both to see what was best , they both worked with one problem

It seems it loops thru the folders a second time a list them all again

Any thoughts or suggestions?

 

Thanks

Tom

Perhaps you can show the code that you ran to produce those results. Here’s a test you can run to confirm the results.

This test expects c:\temp\demo to exist already.

$SomePath=”c:\temp\demo”

1..4 | % {
    $folder = New-Item $SomePath -Name "Folder$_" -ItemType Directory
    if($_ % 2 -eq 0)
    {
        $subfolder = New-Item -Path $folder -Name "Folder$_" -ItemType Directory
        if($subfolder -match '4')
        {
            $null = New-Item -Path $subfolder -Name "File$_" -ItemType File
        }
        if($_ % 3 -eq 0)
        {
            $null = New-Item -Path $subfolder -Name "File$_" -ItemType File
        }
    }
    if($_ % 3 -eq 0)
    {
        $null = New-Item -Path $folder -Name "File$_" -ItemType File
    }
}
 
Get-ChildItem -Path $somepath -Recurse -Directory |
    Where-Object {!($_.getfilesysteminfos())} |
        Select-Object -ExpandProperty fullname

There will be 4 folders created in demo one of them being empty. It also creates 4 subfolders and one of those is empty. The contents are a mix of files/folders to ensure correct behavior. The output correctly lists only the two empty folders.

C:\temp\demo\Folder1
C:\temp\demo\Folder2\Folder2