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

I have this POGO class (simple putter getter) which 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 that the last line is a placeholder for more complex logic to come later.

This breaks into an Add-Type with this error message for every get / set in the file.

"MyApp.VM.MyClassVM.CtrId.get" must declare the body because it is not marked abstract or external

Any information on what I am doing wrong will be greatly appreciated.

+3
source share
3 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

Conclusion:

CtrId    : 500
CtrName  : Testing
CtrPhone : 555-1212
CtrZip   : 12345
AddDate  : 1/28/2011 6:16:26 PM
+5
source

, # v3 -Language CSharpVersion3 Add-Type.

@voodoomsr, New-Object, Add-Type, @Chuck -PassThru.

Build-POGO:

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

    $AllLines = (Get-Content $FileName) -join "`n"
    $type = Add-Type -TypeDefinition $AllLines -Language CSharpVersion3 -PassThru

    New-Object $type
}
+3

You have 2 errors, 1: missing type namespace, 2: you are not typing anything. I give you a possible correction:

$ClassHandle = New-Object -typeName MyApp.VM.$ClassName
$ClassHandle | fl     #basic way to print the members

more beautiful printing of elements (Properties)

 $ClassHandle | gm -MemberType Property |
 % {write-host $_.name  -for red -nonewline; 
 [console]::setcursorposition(15,[console]::cursortop);
 write-host $classhandle.($_.name) -f white}
+1
source

Source: https://habr.com/ru/post/1786702/


All Articles