3

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?

1 Answer 1

4

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)

6
  • I get an output of "Hi" and my $Host.Version gives 3.2.0.2237
    – SteB
    Dec 11, 2012 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, 2012 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, 2012 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, 2012 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, 2012 at 18:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .