Powershell test if folder empty
PowershellPowershell Problem Overview
In Powershell, how do I test if a directory is empty?
Powershell Solutions
Solution 1 - Powershell
If you are not interested in hidden or system files you can also use Test-Path
To see if it exists a file in directory .\temp
you can use :
Test-Path -Path .\temp\*
or shortly :
Test-Path .\temp\*
Solution 2 - Powershell
Try this...
$directoryInfo = Get-ChildItem C:\temp | Measure-Object
$directoryInfo.count #Returns the count of all of the objects in the directory
If $directoryInfo.count -eq 0
, then your directory is empty.
Solution 3 - Powershell
To prevent enumerating each file under c:\Temp (which can be time consuming), we can do somethings like this:
if((Get-ChildItem c:\temp\ -force | Select-Object -First 1 | Measure-Object).Count -eq 0)
{
# folder is empty
}
Solution 4 - Powershell
filter Test-DirectoryEmpty {
[bool](Get-ChildItem $_\* -Force)
}
Solution 5 - Powershell
One line:
if( (Get-ChildItem C:\temp | Measure-Object).Count -eq 0)
{
#Folder Empty
}
Solution 6 - Powershell
Simple approach
if (-Not (Test-Path .\temp*)
{
#do your stuff here
}
you can remove -Not
if you want enter the 'if' when files are present
Solution 7 - Powershell
You can use the method .GetFileSystemInfos().Count
to check the count of directories. Microsoft Docs
$docs = Get-ChildItem -Path .\Documents\Test
$docs.GetFileSystemInfos().Count
Solution 8 - Powershell
Just adding to JPBlanc, if directory path is $DirPath, this code also works for paths including square bracket characters.
# Make square bracket non-wild card char with back ticks
$DirPathDirty = $DirPath.Replace('[', '`[')
$DirPathDirty = $DirPathDirty.Replace(']', '`]')
if (Test-Path -Path "$DirPathDirty\*") {
# Code for directory not empty
}
else {
# Code for empty directory
}
Solution 9 - Powershell
It's a waste to get all files and directories and count them only to determine if directory is empty. Much better to use .NET EnumerateFileSystemInfos
$directory = Get-Item -Path "c:\temp"
if (!($directory.EnumerateFileSystemInfos() | select -First 1))
{
"empty"
}
Solution 10 - Powershell
#################################################
# Script to verify if any files exist in the Monitor Folder
# Author Vikas Sukhija
# Co-Authored Greg Rojas
# Date 6/23/16
#################################################
################Define Variables############
$email1 = "[email protected]"
$fromadd = "[email protected]"
$smtpserver ="mailrelay.conoso.com"
$date1 = get-date -Hour 1 -Minute 1 -Second 1
$date2 = get-date -Hour 2 -Minute 2 -Second 2
###############that needs folder monitoring############################
$directory = "C:\Monitor Folder"
$directoryInfo = Get-ChildItem $directory | Measure-Object
$directoryInfo.count
if($directoryInfo.Count -gt '0')
{
#SMTP Relay address
$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
#Mail sender
$msg.From = $fromadd
#mail recipient
$msg.To.Add($email1)
$msg.Subject = "WARNING : There are " + $directoryInfo.count + " file(s) on " + $env:computername + " in " + " $directory
$msg.Body = "On " + $env:computername + " files have been discovered in the " + $directory + " folder."
$smtp.Send($msg)
}
Else
{
Write-host "No files here" -foregroundcolor Green
}
Solution 11 - Powershell
Example of removing empty folder:
IF ((Get-ChildItem "$env:SystemDrive\test" | Measure-Object).Count -eq 0) {
remove-Item "$env:SystemDrive\test" -force
}
Solution 12 - Powershell
$contents = Get-ChildItem -Path "C:\New folder"
if($contents.length -eq "") #If the folder is empty, Get-ChileItem returns empty string
{
Remove-Item "C:\New folder"
echo "Empty folder. Deleted folder"
}
else{
echo "Folder not empty"
}
Solution 13 - Powershell
#Define Folder Path to assess and delete
$Folder = "C:\Temp\Stuff"
#Delete All Empty Subfolders in a Parent Folder
Get-ChildItem -Path $Folder -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse
#Delete Parent Folder if empty
If((Get-ChildItem -Path $Folder -force | Select-Object -First 1 | Measure-Object).Count -eq 0) {Remove-Item -Path $CATSFolder -Force -Recurse}
Solution 14 - Powershell
Getting a count from Get-ChildItem can provide false results because an empty folder or error accessing a folder could result in a 0 count.
The way I check for empty folders is to separate out errors:
Try { # Test if folder can be scanned
$TestPath = Get-ChildItem $Path -ErrorAction SilentlyContinue -ErrorVariable MsgErrTest -Force | Select-Object -First 1
}
Catch {}
If ($MsgErrTest) { "Error accessing folder" }
Else { # Folder can be accessed or is empty
"Folder can be accessed"
If ([string]::IsNullOrEmpty($TestPath)) { # Folder is empty
" Folder is empty"
}
}
The above code first tries to acces the folder. If an error occurs, it outputs that an error occurred. If there was no error, state that "Folder can be accessed", and next check if it's empty.
Solution 15 - Powershell
After looking into some of the existing answers, and experimenting a little, I ended up using this approach:
function Test-Dir-Valid-Empty {
param([string]$dir)
(Test-Path ($dir)) -AND ((Get-ChildItem -att d,h,a $dir).count -eq 0)
}
This will first check for a valid directory (Test-Path ($dir)
). It will then check for any contents including any directories, hidden file, or "regular" files** due to the attributes d
, h
, and a
, respectively.
Usage should be clear enough:
PS C_\> Test-Dir-Valid-Empty projects\some-folder
False
...or alternatively:
PS C:\> if(Test-Dir-Valid-Empty projects\some-folder){ "empty!" } else { "Not Empty." }
Not Empty.
** Actually I'm not 100% certain what the defined effect of of a
is here, but it does in any case cause all files to be included. The documentation states that ah
shows hidden files, and I believe as
should show system files, so I'm guessing a
on it's own just shows "regular" files. If you remove it from the function above, it will in any case find hidden files, but not others.
Solution 16 - Powershell
One line for piping, by also using the GetFileSystemInfos().Count
with a test :
gci -Directory | where { !@( $_.GetFileSystemInfos().Count) }
will show all directories which have no items. Result:
Directory: F:\Backup\Moving\Test
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 5/21/2021 2:53 PM Test [Remove]
d----- 5/21/2021 2:53 PM Test - 1
d----- 5/21/2021 2:39 PM MyDir [abc]
d----- 5/21/2021 2:35 PM Empty
I post this because I was having edge-case issues with names that contained brackets [ ]
; failure was when using other methods and the output piped to Remove-Item
missed the directory names with brackets.