2012-07-11 198 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