Powershell – How to Handle Null Objects in Foreach Loop

powershell

I'm listing all backups in a given directory:

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

If I set it to deliberately return no files (.addDays(-600) then the following prints "Empty" (as expected):

if (!$backups)
{
    "Empty"
}

If I try to list the names with an empty $backups variable:

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

I get nothing (as expected), if I change this to:

"test"+ $file.FullName;

then I get a single "test" under the "Empty". How is this possible if $backups is empty?

Best Answer

This is a "feature" of Powershell. Your $backups may contain multiple $null values, as well as non-null, so Powershell must iterate the object to process the foreach. The fact the we both see $backup as a single-value scalar ($null in this case) doesn't matter, to MS at least... :)

See this Microsoft Connect Bug Report for more details -- It is "fixed" in Powershell v3.

On v2:

PS H:\> foreach ( $i in $null ) { "Hi" }
Hi

On v3:

PS H:\> foreach ( $i in $null ) { "Hi" }

(No output)