Why is an empty PowerShell pipeline not the same as null?

前端 未结 2 1922
深忆病人
深忆病人 2020-12-09 21:47

I am trying to understand the behavior of the @() array constructor, and I came across this very strange test.

It seems that the value of an empty pipeline is \"not

2条回答
  •  Happy的楠姐
    2020-12-09 22:48

    The reason you're experiencing this behaviour is becuase $null is a value. It's a "nothing value", but it's still a value.

    PS P:\> $y = 1,2,3,4 | ? { $_ -ge 5 }
    
    PS P:\> Get-Variable y | fl *
    
    #No value survived the where-test, so y was never saved as a variable, just as a "reference"
    
    Name        : y
    Description : 
    Value       : 
    Visibility  : Public
    Module      : 
    ModuleName  : 
    Options     : None
    Attributes  : {}
    
    
    PS P:\> $z = $null
    
    
    PS P:\> Get-Variable z | fl *
    
    #Our $null variable is saved as a variable, with a $null value.
    
    PSPath        : Microsoft.PowerShell.Core\Variable::z
    PSDrive       : Variable
    PSProvider    : Microsoft.PowerShell.Core\Variable
    PSIsContainer : False
    Name          : z
    Description   : 
    Value         : 
    Visibility    : Public
    Module        : 
    ModuleName    : 
    Options       : None
    Attributes    : {}
    

    The way @() works, is that it guarantees that the result is delievered inside a wrapper(an array). This means that as long as you have one or more objects, it will wrap it inside an array(if it's not already in an array like multiple objects would be).

    $y is nothing, it's a reference, but no variable data was stored. So there is nothing to create an array with. $z however, IS a stored variable, with nothing(null-object) as the value. Since this object exists, the array constructor can create an array with that one item.

提交回复
热议问题