2012-07-11 161 views
0

我知道如何执行一个powershell命令并使用C#代码查看它的结果。但我想知道如何执行一组如下相关命令,并得到输出:C#powershell脚本

$x = some_commandlet 
$x.isPaused() 

简单地说,我要访问的$x.isPaused()返回值。

如何将此功能添加到我的C#应用​​程序中?

回答

2

对于这样的命令,最好是创建一个名为管道的东西,并为其提供脚本。我发现了一个很好的例子。你可以进一步了解这个代码和这样的项目here

private string RunScript(string scriptText) 
{ 
    // create Powershell runspace 

    Runspace runspace = RunspaceFactory.CreateRunspace(); 

    // open it 

    runspace.Open(); 

    // create a pipeline and feed it the script text 

    Pipeline pipeline = runspace.CreatePipeline(); 
    pipeline.Commands.AddScript(scriptText); 

    // add an extra command to transform the script 
    // output objects into nicely formatted strings 

    // remove this line to get the actual objects 
    // that the script returns. For example, the script 

    // "Get-Process" returns a collection 
    // of System.Diagnostics.Process instances. 

    pipeline.Commands.Add("Out-String"); 

    // execute the script 

    Collection<psobject /> results = pipeline.Invoke(); 

    // close the runspace 

    runspace.Close(); 

    // convert the script result into a single string 

    StringBuilder stringBuilder = new StringBuilder(); 
    foreach (PSObject obj in results) 
    { 
     stringBuilder.AppendLine(obj.ToString()); 
    } 

    return stringBuilder.ToString(); 
} 

这种方法整齐地做了适当的评论。你也可以直接进入我下载并开始播放的代码项目的链接!

+0

谢谢,它为我工作 – 2012-07-15 16:55:31