How to create a class by reading from another class (.cs) file with Powershell?

Posted by Razcer on Stack Overflow See other posts from Stack Overflow or by Razcer
Published on 2011-01-20T15:23:00Z Indexed on 2011/01/28 23:25 UTC
Read the original article Hit count: 143

Filed under:

I have this POGO ( simple putter getter) class that I am trying to read in PowerShell

using System;
using System.Runtime.Serialization;

namespace MyApp.VM
{
  [Serializable]
  public class MyClassVM
  {
      public Int64 CtrId { get; set; }
      public string CtrName { get; set; }
      public string CtrPhone { get; set; }
      public string CtrZip { get; set; }
      public DateTime AddDate { get; set; }
  }
}

Here is the ps1 code that is trying to read the class from a file.

function Build-Pogo
{
    $FileDir   = "D:\YourDirectoryOfPogo" 
    $ClassName = "MyClassVM"
    $FileName  = $FileDir + "\" + $ClassName + ".cs"

    # Build the class from the file
    $AllLines = [string]::join([environment]::newline, (Get-Content $FileName))
    Add-Type -TypeDefinition $AllLines

    # spin thru each property for class
    $ClassHandle = New-Object -typeName $ClassName
    $ClassHandle | ForEach-Object {Write-Host $_.name -foregroundcolor cyan}
}

*Note the last line is placeholder for more complex logic to come later.

This breaks at the Add-Type with this error message for each get/set in the file.

'MyApp.VM.MyClassVM.CtrId.get' must declare a body because it is not marked abstract or extern

Any info on what I'm doing wrong will be greatly appreciated.

© Stack Overflow or respective owner

Related posts about powershell-v2.0