Abe Miessler
Abe Miessler

Reputation: 85056

How to add items to a System.Collections.Generic.List object using PowerShell?

I have an object that has a List<String> as a member. I tried adding items to this list in the following way:

$myObject.MyList.Add("News")
$myObject.MyList.Add("FAQ")
$myObject.MyList.Add("Events")

But when I check:

$myObject.MyList.Count

It returns 0. Is there a different way I should be doing this?

Snippit from my source code:

    [Personalizable(PersonalizationScope.Shared), WebBrowsable(false)]
    public List<String> SelectedTabs
    {
        get;
        set;
    }

Upvotes: 2

Views: 9288

Answers (2)

Shay Levy
Shay Levy

Reputation: 126732

I'm not a developer but maybe this is what you're looking for:

PS> $list = New-Object System.Collections.Generic.List[System.String]
PS> $list.Add("News")
PS> $list.Add("FAQ")
PS> $list.Add("Events")
PS> $list
News
FAQ
Events    

PS> $list.Count
3

Upvotes: 5

manojlds
manojlds

Reputation: 301147

Works for me:

$source =@"
using System.Collections.Generic;
public class MyClass {
    public List<string> MyList;
    public MyClass(){
    MyList = new List<string>();
    }
}

"@

Add-Type -TypeDefinition $source -Language CSharpVersion3

$myObject = new-object MyClass

$myObject.MyList.Add("test");

$myObject.MyList.Count

Upvotes: 3

Related Questions