Custom type in Powershell with Generics Collection as a member
-
13-12-2019 - |
Question
I would like to declare the following type in my powershell script:
Add-Type @'
public class VirtualMachine {
string Name;
string HostName;
HashSet<string> Dependencies = new HashSet<string>();
}
'@
But the compiler complains about HashSet cannot be found.
If I comment out the HashSet line, the type works fine. I guess I have to tell powershell to load System.Core assembly but I couldn't figured it out.
Please, someone can tell me what am i missing?
Thx in advance.
[EDIT:] With your quick help, I managed to solve my problem. Thx for your time.
This is my final code:
Add-Type -ReferencedAssemblies System.Core @"
using System.Collections.Generic;
public class VirtualMachine {
public string Name;
public string HostName;
public HashSet<string> Dependencies = new HashSet<string>();
}
"@
Solution
Like this:
Add-Type -ReferencedAssemblies System.Core @"
using System.Collections.Generic;
public class VirtualMachine {
public string Name { get; set; }
public string HostName{ get; set; }
public HashSet<string> Dependencies { get; set; }
}
"@
You have to add assembly reference to System.Core
and add a using System.Collections.Generic
in you c# code.
OTHER TIPS
You can add references via the Referenced Assemblies parameter.
Add-Type -ReferencedAssemblies System.Core
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow