PowerShell function will not return an object

I have a simple function that creates a generic list:

function test() { $genericType = [Type] "System.Collections.Generic.List``1" [type[]] $typedParameters = ,"System.String" $closedType = $genericType.MakeGenericType($typedParameters) [Activator]::CreateInstance($closedType) } $a = test 

The problem is that $a always null, regardless of what I'm trying to do. If I execute the same code outside the function, it works correctly.

Thoughts?

+4
source share
2 answers

IMHO, that the trap number 1. If you return an object from a function that is somehow enumerable (I don’t know for sure whether the IEnumerable implementation is the only case), PowerShell expands the object and returns the elements in it.

Your new list was empty, so nothing was returned. To make it work, just use this:

 ,[Activator]::CreateInstance($closedType) 

This will create one array of elements to be expanded, and the element (general list) is assigned $a .

Additional Information

Here is a list of related questions to help you understand what is happening:


Note: you do not need to declare the title of the function as a bracket. If you need to add parameters, the function will look like this:

 function test { param($myParameter, $myParameter2) } 

or

 function { param( [Parameter(Mandatory=true, Position=0)]$myParameter, ... again $myParameter2) ... 
+8
source

An easier way to work with generics. This does not directly address the [Activator] approach, although

 Function test { New-Object "system.collections.generic.list[string]" } (test).gettype() 
+3
source

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


All Articles