Why can I call GetType () on an empty array, but not when it returns from a function

In my never-ending quest to understand Powershell, someone can explain this behavior 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 maybe not), in both cases the presence of tubular elements has the same behavior:

 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." 

Color bothers me. Can someone explain this?

+5
source share
1 answer

This is because when you return an array (and possibly any other collection) from a function, PowerShell puts each element of the array into the pipeline. Thus, GetType() is not actually called in an empty array, but its elements (which are missing).

Inspiration may be to return an array to another array :).

 function fn1{return ,@()} (fn1).GetType() 

Now Powershell will go into the pipeline elements of this "parent" array, which, as it turns out, contains only one element: your empty array. Note that you cannot achieve this with return @(@()) , because external @() only ensures that the returned result will be the array that it already is.

+4
source

Source: https://habr.com/ru/post/1208803/


All Articles