Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 716
Razcer Avatar asked Dec 05 '25 08:12

Razcer


1 Answers

Try this code, it worked for me.

$type = Add-Type -Path $FileName -PassThru

$x = New-Object $type
$x.CtrId = 500
$x.CtrName = 'Testing'
$x.CtrPhone = '555-1212'
$x.CtrZip = '12345'
$x.AddDate = Get-Date

$x

Output:

CtrId    : 500
CtrName  : Testing
CtrPhone : 555-1212
CtrZip   : 12345
AddDate  : 1/28/2011 6:16:26 PM
like image 138
Chuck Heatherly Avatar answered Dec 08 '25 13:12

Chuck Heatherly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!