How can Get-ChildItem be tested for no results (zero files)? How can Get-ChildItem be tested for no results (zero files)? powershell powershell

How can Get-ChildItem be tested for no results (zero files)?


Try wrapping in @(..). It creates always an array:

$Files = @(Get-ChildItem $BackupPath_Root -include *.bak -recurse            | where {$_.CreationTime  -le $DelDate_Backup })if ($Files.length -eq 0) {  write-host "   no files to delete." } else {  ..}


When there are no files, $Files is equal to $null, so as EBGreen suggests you should test against $null. Also, $Files.Count is only useful when the result is a collection of files. If the result is a scalar (one object) it won't have a count property and the comparison fails.

Performance tip: when you need to search for just one extension type, use the -Filter parameter (instead of -Include) as it's filtering on the provider level.


The variable evaluates to a null-valued expression when scanned folder is empty. You can use:

if (!$Files) {# ...}