Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm stumped here on what seems to be a simple problem; so sorry for any bone-headed-ness over here.

I have script that cleans up defunct backup files. After identifying the files I loop over and print out what's being dumped. My problem arises trying to provide feedback/testing when there are zero defunct files. The script looks like...

$Files = Get-ChildItem $BackupPath_Root -include *.bak -recurse             | where {$_.CreationTime  -le $DelDate_Backup }    if ( $Files -eq "" -or $Files.Count  -eq 0 ) {     write-host "   no files to delete."    #<-- this doesn't print when no files } else {    foreach ($File in $Files) {       write-host “$File”        Remove-Item $File | out-null    }  } 

The if checking for no files doesn't catch the no file condition. What is the appropriate way to test $Files for no results ?

like image 749
EBarr Avatar asked Jul 28 '11 13:07

EBarr


2 Answers

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 {   .. } 
like image 155
stej Avatar answered Oct 04 '22 11:10

stej


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.

like image 34
Shay Levy Avatar answered Oct 04 '22 11:10

Shay Levy