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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With