Using Powershell for the first time here, so please go easy on me...

I've written a script that checks a directory and, for any directory inside that is empty, it is to be deleted. The problem I'm having is with directories containing brakets -> [] in the directory name. Even if the directory isn't empty, it's still being deleted. Can anyone help? Here's the code I'm using:

$path = "C:\path\to\directory"
Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

I don't fully understand the code above, I found it online. But it's working for directories that don't have the brackets.

For a directory with the name of "SummerPhotos" that contains a file, the directory is not deleted. -> Good

For a directory that is empty, it is deleted. -> Good

For a directory named "SummerPhotos[2009]", it's being deleted even if it contains a file. -> Bad

I googled and read that powershell treats brackets as wildcards, but I'm not sure how to get around it. Any help would be appreciated.


  • If you don't want to remove non-empty directories, why are you using -Recurse in the first place? – user1686 Aug 6 '17 at 12:22
  • In PowerShell Get-ChildItem the [] denote a range, to avoid this don't use -Path but -LiteralPath inside the Where-Ob ject – LotPings Aug 6 '17 at 13:39
  • @grawity How to get the last of some stacked directories if not recursing? – LotPings Aug 6 '17 at 13:46
  • In PowerShell Get-ChildItem the [] denote a range, to avoid this don't use -Path but -LiteralPath inside the Where-Object
  • To avoid possible irritations with $env:path choose a different variable name.

$Mypath = "C:\path\to\directory"
Get-ChildItem -Path $Mypath -Recurse -Force | 
  Where-Object { $_.PSIsContainer -and (Get-ChildItem -LiteralPath $_.FullName -Recurse -Force | 
                                        Where-Object { !$_.PSIsContainer }) -eq $null } | 
    Remove-Item -Force -Recurse -Confirm

In more recent PowerShell versions you can use Get-ChildItem parameters -Directoy and -File instead of Where {$_.PSIsContainer}

$Mypath = "C:\path\to\directory"
Get-ChildItem -Path $Mypath -Recurse -Force -Directory -EA 0 | 
  Where-Object { (Get-ChildItem -LiteralPath $_.FullName -Recurse -Force -File -EA 0 ) -eq $null } | 
    Remove-Item -Force -Recurse -Confirm

  • -EA 0 is an abbreviation for -ErrorAction SilentlyContinue
  • while testing I suggest using -WhatIf or -Confirm in the Remove-Item cmdlet
| improve this answer | |
  • Hey that worked beautifully. Thanks so much!!! – D. Hill Aug 6 '17 at 20:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.