Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer 1

up vote 3 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" }
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 3.2.0.2237 –  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 3.2.0.2237 for $Host.Version instead of the "real" powershell.exe version. –  jscott Dec 11 '12 at 18:10
show 1 more comment

Your Answer

 
discard

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.