Protect foreach loop when empty list

Posted by SteB on Server Fault See other posts from Server Fault or by SteB
Published on 2012-12-13T10:05:32Z Indexed on 2012/12/13 11:06 UTC
Read the original article Hit count: 147

Filed under:

Using Powershell v2.0 I want to delete any files older than X days:

$backups = Get-ChildItem -Path $Backuppath | 
                Where-Object {($_.lastwritetime -lt (Get-Date).addDays(-$DaysKeep)) -and (-not $_.PSIsContainer) -and ($_.Name -like "backup*")}

foreach ($file in $backups)
{
    Remove-Item $file.FullName;
}

However, when $backups is empty I get: Remove-Item : Cannot bind argument to parameter 'Path' because it is null.

I've tried:

  1. Protecting the foreach with if (!$backups)
  2. Protecting the Remove-Item with if (Test-Path $file -PathType Leaf)
  3. Protecting the Remove-Item with if ([IO.File]::Exists($file.FullName) -ne $true)

None of these seem to work, what if the recommended way of preventing a foreach loop from being entered if the list is empty?

© Server Fault or respective owner

Related posts about powershell