Powershell enters foreach loop with null object

Posted by SteB on Server Fault See other posts from Server Fault or by SteB
Published on 2012-12-11T17:03:04Z Indexed on 2012/12/11 17:06 UTC
Read the original article Hit count: 204

Filed under:

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?

© Server Fault or respective owner

Related posts about powershell