Reputation: 12334
In my never-ending quest to understand Powershell better can someone please explain this behaviour to me:
function fn1{return @()}
(@()).GetType() #does not throw an error
(fn1).GetType() #throws error "You cannot call a method on a null-valued expression."
Why does returning a value from a function make it "different"?
Interestingly (or perhaps not), piping to get-member exhibits the same behaviour in both cases:
function fn1{return @()}
@() | gm #does throw an error "You cannot call a method on a null-valued expression."
fn1 | gm #does throw an error "You cannot call a method on a null-valued expression."
Colour me confused. Can someone explain this?
Upvotes: 5
Views: 582
Reputation: 13181
This happens because when you return an array (and probably any other collection) from function, PowerShell will put each element of array into a pipeline. So GetType()
is actually not being called on empty array, but it's elements (that are missing).
The soulution could be to return your array in another array :).
function fn1{return ,@()}
(fn1).GetType()
Now Powershell will pass into a pipeline elements of this "parent" array, which happens to containt only one element: your empty array.
Please note that you can't achieve that by return @(@())
, because external @()
only assures that result returned will be an array, which it already is.
Upvotes: 4