2011-01-20 56 views
3

我有這個POGO(簡單的推杆吸氣)類,我試圖在PowerShell中如何使用Powershell從另一個類(.cs)文件中讀取來創建類?

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; } 
    } 
} 

閱讀下面是試圖從文件中讀取類中的PS1代碼。

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} 
} 

*請注意,最後一行是更復雜的邏輯的佔位符,以後出現。

對於文件中的每個獲取/設置,這會在添加類型中出現此錯誤消息。

「MyApp.VM.MyClassVM.CtrId.get」,因爲它沒有標記上,我做錯了什麼,將不勝感激抽象或EXTERN

任何信息必須聲明主體。

回答

5

試試這個代碼,它爲我工作。

$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 

輸出:

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

你有2個錯誤,1:類型,2失蹤命名空間:不打印任何東西。 我給你一個可能的修正:

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

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

由於您使用您的類型定義屬性的快捷方式,你需要確保編譯成員(屬性)的更漂亮的印花使用C#v3在Add-Type命令中使用-Language CSharpVersion3

由於@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 
} 
相關問題