2012-07-11 3 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(); 
} 

이 방법

깔끔하게 적절한 의견이 수행된다. 또한 Code Project 링크를 직접 다운로드하여 다운로드하여 시작할 수 있습니다!

+0

감사합니다. –