2014-09-05 21 views
1

我發現了一篇technet博客文章,表示可以讓PowerShell使用C#代碼。 文章:Using CSharp (C#) code in Powershell scripts讓PowerShell腳本使用C#代碼,然後將參數傳遞給Main方法

我發現我需要的C#代碼在PowerShell中工作的格式,但如果它沒有通過Main方法的參數([namespace.class]::Main(foo))腳本拋出一個錯誤。

有沒有一種方法,我可以傳遞一個「開」或「關」字符串的主要方法,然後根據哪個字符串傳遞運行if語句?如果這是可能的,你可以提供示例和/或鏈接?

下面是我目前試圖構建我的代碼的方式。

$Assem = @(//assemblies go here) 

$source = @" 
using ...; 

namespace AlertsOnOff 
{ 
    public class onOff 
    { 
     public static void Main(string[] args) 
     { 
      if(args == on) 
       {//post foo } 
      if(arge == off) 
       { //post bar } 

     } 
"@ 

Add-Type -TypeDefinition $Source -ReferencedAssumblies $Assem 
[AlertsOnOff.onOff]::Main(off) 

#PowerShell script code goes here. 

[AlertsOnOff.onOff]::Main(on) 

回答

1

好吧,如果您要編譯並運行C#代碼,您需要編寫有效的C#代碼。在PowerShell方面,如果您從PowerShell調用Main,則需要將它傳遞給參數。 PowerShell會自動將一個參數放入數組中,但如果您沒有參數,它將不會插入參數。這就是說,它不清楚爲什麼這是一種主要方法。這不是可執行文件。很可能只有兩種靜態方法,TurnOnTurnOff。下面的代碼編譯並運行,如你所見:

$source = @" 
using System; 

namespace AlertsOnOff 
{ 
    public class onOff 
    { 
     public static void Main(string[] args) 
     { 
      if(args[0] == `"on`") 
      { 
        Console.WriteLine(`"foo`"); 
      } 
      if(args[0] == `"off`") 
      { 
        Console.WriteLine(`"bar`"); 
      } 
     } 
    } 
} 
"@ 

Add-Type -TypeDefinition $Source 
[AlertsOnOff.onOff]::Main("off") 

# Other code here 

[AlertsOnOff.onOff]::Main("on") 
+0

我同意邁克在這裏。 OP的代碼看起來像是一個帶有標準Main入口點的exe文件。將其修改爲圖書館將會更直接。另外,如果您在這裏使用單引號字符串,則不必在其中使用雙引號。 :-) – 2014-09-05 22:52:16

相關問題