开发者

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 = "M开发者_JS百科yClassVM"
    $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.


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


Since you are using property shortcuts in your type definition, you need to make sure to compile using C# v3 by using -Language CSharpVersion3 in the Add-Type command.

As @voodoomsr pointed out, you must supply the Namespace for New-Object, or you can return the type from Add-Type as @Chuck did with the -PassThru parameter.

Here is an example of the Build-POGO function:

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
}


You have 2 errors, 1: the missing Namespace of the type, 2: you are not printing anything. I give you a possible correction:

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

a more beautiful print of the members(Properties)

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜