2011-11-30 76 views
5

我有一个C#类,它应该通过传递一个Log对象来执行一个Powershell脚本。日志完全用C#编写,并且应该在C#代码和Powershell之间共享,以实现通用日志记录。从C#传递一个自定义对象到Powershell

有人能告诉我如何将自定义对象从C#传递到Powershell并在那里使用它?

+0

你只需要通过类或实例? – JNK

+0

Log的一个实例。 – naspras

回答

1

您可以通过编辑您的Log类为一个程序集共享PowerShell和C#之间的类,并在PowerShell中使用LoadFile(应在V1和V2工作)

$lib = [System.Reflection.Assembly]::LoadFile('path to your dll'); 
$lib.Log("Terrible things have happened!") 

但是,如果你想分享一个实例PowerShell和C#之间的类可以使用SessionStateProxy.SetVariable

+0

Assembly.LoadFile返回一个程序集,所以我认为这里缺少一行。另外考虑'Add-Type -Path'。 –

1

如果您只需要在powershell脚本中使用该类,则可以将实际的C#代码放入脚本本身,并将其用作类型的定义。

There is a tutorial here.

基本上你使用Add-Type -TypeDefinition <C# code> -Language CSharp

+0

我的情况有点不同。 Powershell脚本位于C#程序之外的文件中,我需要使用Log作为参数调用此文件。 – naspras

0

的参考system.management.automation.dll添加到您的项目并使用PowerShell Class。 见的例子有,这几乎是准备好了,改线

ps.AddCommand("Get-Process"); 

喜欢的东西:

ps.AddCommand(<script-path/name-of-script-in-path>).AddParameter("Log", logInstance); 

它讲述与参数Log其值是一个实例logInstance是调用脚本通过脚本传递。该脚本应该有参数Log并在其代码中使用它作为$Log

param($Log) 

$Log.Write("Begin ...") 
... 
$Log.Write("End ...") 
+0

我要试试这个。您能否告诉我如何从PowerShell脚本本身访问传递的参数? – naspras

+0

@naspras - 我已经添加了这个回答。 –

2

我相信它使用运行空间将解决你的问题。一个很好的解释和例子,你可以在下面找到这个链接:http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C

只是一个通用的想法,如何使用它们。

,如果您有脚本:

param($logger2) 
$logger2.Write("logger2 Write was called"); 
$logger.Write("logger Write was called"); 

,你想替补多logger2和记录器使用下面的代码:

String scriptContent = // get script content 
Logger logger = new Logger(); 
Logger2 logger2 = new Logger2(); 
// create ps runspace 
using (Runspace runspace = RunspaceFactory.CreateRunspace()) 
{ 
    // start session 
    runspace.Open(); 
    // set variables 
    runspace.SessionStateProxy.SetVariable("logger", logger); 
    // supply commands 
    using (Pipeline pipeline = runspace.CreatePipeline()) 
    { 
     // create ps representation of the script 
     Command script = new Command(scriptContent, true, false); 
     // suppy parameters to the script 
     script.Parameters.Add(new CommandParameter("logger2", logger2)); 
     // send script to pipeline 
     pipeline.Commands.Add(script); 
     // execute it 
     Collection<PSObject> results = pipeline.Invoke(); 
     // close runspace 
     runspace.Close(); 
    } 
} 
相关问题