Null lists behavior in Powershell

Powershell is weird. We know that.

But this blows my mind.

Consider the following line of code:

$result = Get-ChildItem "foo*"

foreach($bar in $result)
	Write-Host ("Item name: {0}" -f $bar.FullName)

What will this print?

When a matching file is found it will print its full name.

What if it doesn’t print? Every sane person will say: nothing. Powershell is not sane. This is the result:

Property 'FullName' cannot be found on this object. Make sure that it exists.
At C:\Users\Kristof Mattei\Desktop\test.ps1:9 char:39
+     Write-Host ("Item name: {0}" -f $bar. <<<< FullName)
    + CategoryInfo          : InvalidOperation: (.:OperatorToken) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFoundStrict


Why on earth would the foreach start?

The list is $null, not even empty. Do I need to prefix every single foreach with a null check to make sure it doesn’t start?