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:
- Protecting the foreach with
if (!$backups)
- Protecting the Remove-Item with
if (Test-Path $file -PathType Leaf)
- 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?
Best Answer
With Powershell 3 the
foreach
statement does not iterate over$null
and the issue described by OP no longer occurs.From the Windows PowerShell Blog post New V3 Language Features:
For PowerShell
$PSVersionTable.PSVersion.Major -le 2
see the following for original answer.You have two options, I mostly use the second.
Check
$backups
for not$null
. A simpleIf
around the loop can check for not$null
Or
Initialize
$backups
as a null array. This avoids the ambiguity of the "iterate empty array" issue you asked about in your last question.Sorry, I neglected to provide an example integrating your code. Note the
Get-ChildItem
cmdlet wrapped in the array. This would also work with functions which could return a$null
.