24. December 2008
Andy Schneider
There may be, on some occassion, a need to create a class with a set of properties in PowerShell. This can’t be done natively, but it can be done with some very simple C# syntax, thanks to C# version 3.0, which is really a new compiler as opposed to a new version of .NET. The base class library is the same. Here is a very basic class with four properties.
1: PS C:\Users\andy.schneider> $csharp = @"
2: >> public class Andy
3: >> {
4: >> public int age {get;set;}
5: >> public string firstName {get;set;}
6: >> public string lastName {get;set;}
7: >> public string blog {get;set;}
8: >> }
9: >> "@
10: >>
11: PS C:\Users\andy.schneider>
But we still have to get it into PowerShell. We can use the Add-Type Cmdlet to do this, but it will fail unless we use the C# 3.0 compiler under the covers. We can specify the language we are using with the –Language parameter. I know CSharp30 is wrong, but I like to give it garbage so it will tell me what the valid languages are. Because it takes an ENUM we can find out that CsharpVersion3 is a valid language.
1: PS C:\Users\andy.schneider>
2: PS C:\Users\andy.schneider> add-type $csharp -Language Csharp30
3: Add-Type : Cannot bind parameter 'Language'. Cannot convert value "Csharp30" to type "Microsoft.PowerShell.Commands.Lan
4: guage" due to invalid enumeration values. Specify one of the following enumeration values and try again. The possible e
5: numeration values are "CSharp, CSharpVersion3, VisualBasic, JScript".
6: At line:1 char:27
7: + add-type $csharp -Language <<<< Csharp30
8: PS C:\Users\andy.schneider> add-type $csharp -Language CsharpVersion3
All right, now we are ready to to after running the command on line 8.
We can create a new object of type Andy and set it to $andy
1: PS C:\Users\andy.schneider> $andy = new-object andy
2: PS C:\Users\andy.schneider> $andy | gm
3:
4:
5: TypeName: Andy
6:
7: Name MemberType Definition
8: ---- ---------- ----------
9: Equals Method System.Boolean Equals(Object obj)
10: GetHashCode Method System.Int32 GetHashCode()
11: GetType Method System.Type GetType()
12: ToString Method System.String ToString()
13: age Property System.Int32 age {get;set;}
14: blog Property System.String blog {get;set;}
15: firstName Property System.String firstName {get;set;}
16: lastName Property System.String lastName {get;set;}
Now we have a full blown object with properties and we can create new instances of them all day long, and the C# was pretty darn straight forward.