PowerShell: Check if Get-ChildItem Returns No Results


You can use the Get-ChildItem cmdlet in PowerShell to retrieve all files in a particular directory.

Occasionally you may want to check if the Get-ChildItem cmdlet returns no results.

You can use the following syntax to do so:

$results = @(Get-ChildItem)

if ($results.length -eq 0) {
  Write-Host "No Files" 
} else {
  Write-Host "At Least One File"
}

This syntax works by storing the results of the Get-ChildItem cmdlet in an array named $results and then by using an if else statement to check if the length property of the array is equal to zero or not.

The following example shows how to use this syntax in practice.

Example: Check if Get-ChildItem Returns No Results in PowerShell

Suppose that our current directory has the following path:

  • C:\Users\bobbi\data1

We can use the Get-ChildItem cmdlet to first view all of the files in this current directory:

We can see that this directory contains six total files.

We can use the following syntax to check if the Get-ChildItem cmdlet returns no results or not:

$results = @(Get-ChildItem)

if ($results.length -eq 0) {
  Write-Host "No Files" 
} else {
  Write-Host "At Least One File"
}

The following screenshot shows how to use this syntax in practice:

PowerShell check if Get-ChildItem is empty

This returns the output “At Least One File” to indicate that the Get-ChildItem cmdlet returned at least one file.

Suppose instead that our current directory has the following path:

  • C:\Users\bobbi\data2

We can use the Get-ChildItem cmdlet to first view all of the files in this current directory:

We can see that this directory contains no files.

We can use the following syntax to check if the Get-ChildItem cmdlet returns no results or not:

$results = @(Get-ChildItem)

if ($results.length -eq 0) {
  Write-Host "No Files" 
} else {
  Write-Host "At Least One File"
}

The following screenshot shows how to use this syntax in practice:

PowerShell check if Get-ChildItem returns any results

This returns the output “No Files” to indicate that the Get-ChildItem cmdlet returns no files.

Note: You can find the complete documentation for the Get-ChildItem cmdlet in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Use Get-ChildItem with Filter
PowerShell: How to Use Get-ChildItem with Multiple Filters
PowerShell: How to Use Get-ChildItem to Get Full Path of Files
PowerShell: How to Use Get-ChildItem to Return Files Only

Leave a Reply