Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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)

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

foreach ($file in $backups)

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?

share|improve this question
up vote 4 down vote accepted

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" }

On v3:

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

(No output)

share|improve this answer
I get an output of "Hi" and my $Host.Version gives – SteB Dec 11 '12 at 17:42
@SteB I cannot find that version of PowerShell -- are you using PowerGui? Can you provide $Host.Version from the actual powershell.exe binary, or even $PSVersionTable? – jscott Dec 11 '12 at 17:51
Yes, I am using PowerGUI. My powershell.exe in WindowsPowerShell/v1.0 is 6.1.7600.16385. $PSVersionTable gives CLRVersion: 4.0.30319.17929 and WSManStackVersion: 2.0 – SteB Dec 11 '12 at 17:57
@SteB Yep, your PowerGUI is v3.2.0.2237, your Powershell is v2. $PSVersionTable should have listed PSVersion as well, but your powershell.exe binary 6.1.7600.16385 confirms v2. – jscott Dec 11 '12 at 17:58
You can see Get-Help about_Automatic_Variables, in particular the $Host section, to understand how PowerGUI is returning for $Host.Version instead of the "real" powershell.exe version. – jscott Dec 11 '12 at 18:10

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.