2012-06-06 2 views
0

powershell cmdlets를 많이 포함하는 .ps1 파일에서 powershell cmdlet을 실행하는 코드가 있습니다. 나는이 예외cmdlet (함수?)의 .ps1 파일에있는 powershell cmdlet (함수?)을 실행하는 코드

'새-BuildCVFromSql'는 cmdlet을, 기능, 스크립트 파일 또는 실행할 수있는 프로그램의 이름으로 인식되지 않는 용어를 얻을 그것을 실행합니다. 맞춤법 검사 의 이름을 확인하거나 경로가 포함되어 있으면 경로가 인지 확인하고 다시 시도하십시오.

private void RunPowerShellCommandToBuildCV() 
{ 
    string BigWindow = ""; 
    string FileNamePopup = ""; 

    TestPopup(ref BigWindow, ref FileNamePopup); 

    string psScriptPath = @"D:\Project Files\CIS3G\Webapp\_Powershell\JcdcCv.psm1"; 
    string psScript = string.Empty; 

    if(File.Exists(psScriptPath)) 
     psScript = File.ReadAllText(psScriptPath); 
    else 
     throw new FileNotFoundException("Wrong path for the script file"); 

    // init the powershell runspace and pipeline - EWB 
    Runspace runSpace = RunspaceFactory.CreateRunspace(); 
    runSpace.Open(); 

    // set execution policy - EWB 
    RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runSpace); 
    runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); 

    Pipeline pipeline = runSpace.CreatePipeline(); 

    //i tried loading it both of the ways below and no joy load the script from the string - EWB 
    //pipeline.Commands.AddScript(psScript); 

    //load as file - EWB 
    pipeline.Commands.AddScript(psScriptPath, false); 

    //add the outstring command to the pipeline. 
    pipeline.Commands.Add("Out-String"); 


    Command myCommand = new System.Management.Automation.Runspaces.Command("New-BuildCVFromSql"); 

    CommandParameter SqlOrExcelFile       = new CommandParameter("SqlOrExcelFile", @"C:\Documents and Settings\Brown.Ericw\My Documents\tempeval.sql"); 
    CommandParameter Js          = new CommandParameter("Js", "JCDC"); 
    CommandParameter FileName        = new CommandParameter("FileName", @"Evaluation\EvaluationFormPartialListVM"); 

    myCommand.Parameters.Add(SqlOrExcelFile); 
    myCommand.Parameters.Add(Js); 
    myCommand.Parameters.Add(FileName); 

    pipeline.Commands.Add(myCommand); 

    Collection<PSObject> output = pipeline.Invoke(); 
    //foreach (PSObject psObject in output) 
    //{ 

    //System.Diagnostics.Debug.WriteLine ("Object name: " + psObject.); 
    //} 
} 

그래서 분명히 내가 제대로 스크립트의 파일을로드 아니에요? PowerShell ISE/IDE에서 명령을 실행하기 전에 스크립트를 실행해야합니다. 내가 잘못하고있는 것입니까?

다른 사람이 작성한 powershell 스크립트 위에 인터페이스를 넣으려고 했으므로 스크립트 파일을 변경할 수는 없습니다. 다른 사람들이 다른 곳에서 사용하는 beign입니다.

이 .ps1 내가 전화를 노력하고있어 cmdlet을 파일 옆에

는 thusly 히 정의 :

# Create CV Method # 

function New-BuildCVFromSql { 
    param([Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]$SqlFile, 
     [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]$js, 
     [Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]$FileName) 

...    

부록을 :

Problem with calling a powershell function from c#

:이 포스트 당 파이프 라인 대신 PowerShell을 사용하여 시도 이 같은

,하지만 난 같은 예외를 가지고 : (그들은 단지 cmdlet을 내장하지 사용자 정의 함수 작동하기 때문에) 모든 명령 물건을 제거

하고이 일을 :

private void RunPowerShellCommandToBuildCV() 
{ 
    string BigWindow = ""; 
    string FileNamePopup = ""; 

    TestPopup(ref BigWindow, ref FileNamePopup); 

    string psScriptPath = @"D:\Project Files\CIS3G\Webapp\_Powershell\JcdcCv.psm1"; 
    string psScript = string.Empty; 

    if (File.Exists(psScriptPath)) 
     psScript = File.ReadAllText(psScriptPath); 
    else 
     throw new FileNotFoundException("Wrong path for the script file"); 

    // init the powershell runspace and pipeline - EWB 
    using (Runspace runSpace = RunspaceFactory.CreateRunspace()) 
    { 
     runSpace.Open(); 

     // set execution policy - EWB 
     RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runSpace); 
     runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); 

     //Pipeline pipeline = runSpace.CreatePipeline(); 

     PowerShell ps = PowerShell.Create(); 
     ps.Runspace = runSpace; 

     //load as file - EWB 
     ps.AddScript(psScriptPath); 

     ps.AddCommand("New-BuildCVFromSql").AddParameters(new Dictionary<string, string>() 
     { 
      { "SqlOrExcelFile", @"C:\tempeval.sql" }, 
      { "Js", "JCDC" }, 
      { "FileName", @"Evaluation\EvaluationFormPartialListCV" } 
     }); 

     foreach (PSObject result in ps.Invoke()) 
     { 
      Debug.WriteLine ("Object : " + result); 
     } 
    } 

부록 2 대신 depenedencies 중 아무도 그것이 실행되면 laoded되지 않지만 코드를 호출하는 것 같습니다 .. 아직도 찾고 있습니다.

ps.AddScript(@"New-BuildCVFromSql 'C:\Documents and Settings\Brown.Ericw\My Documents\tempeval.sql' JCDC 'Evaluation\EvaluationFormPartialListCV'"); 

는이 달린다 때 depenedencies 전혀로드되지 않습니다하지만 그로보고 아직 .. 코드를 호출하는 것으로 보인다. 이 RunPowerShellCommandToBuildCV()의 두 번째 버전이 작동 ISE ....에서

+0

완전한 소스 코드를 포함한 최종 해결책? – Kiquenet

+0

잘라 내기 및 붙여 넣기 답변을 게시하지 않기로 투표 했습니까? 와우 그게 가혹한 ... 그것은 단지 1 라인 다르다는 그 라인은 코멘트에 있습니다. –

답변

2

를 실행 그러나 만약 스크립트가 추가 된 후 ps.invoke() 누락 된 다음 Invoke()runspace라는 함수가 있다는 것을 알고

//load as file - EWB 
    ps.AddScript(psScriptPath); 
    ps.Invoke(); //<--------- !!!! 
    ps.AddCommand("New-BuildCVFromSql").AddParameters(new Dictionary<string, string>() 
    { 
     { "SqlOrExcelFile", @"C:\tempeval.sql" }, 
     { "Js", "JCDC" }, 
     { "FileName", @"Evaluation\EvaluationFormPartialListCV" } 
    }); 

New-BuildCVFromSql

+0

흠 나는 그것을 시도했지만 이전과 같은 예외가 발생했습니다 ... –

+0

나는 그것을 알아 냈습니다 ps.AddScript (psScriptPath); ps.AddScript (psScript)가 필요했습니다. (파일의 텍스트를로드하지 않고 파일 이름으로로드합니다.) 그리고 내 매개 변수를 보지 못하더라도 실행 중입니다 ... –

+0

@ EricBrown-Cal 왜 'Dictionary '을 전달하고 있습니까? 함수 param 선언을 보면 모든 문자열이있는 것 같습니다. –

0

이것은 내가 어떻게 작동하는지 알려주는 치료법입니다.

private static void Test() 
{ 
    dynamic parameters = new ExpandoObject(); 
    parameters.test= "myImage"; 
    parameters.arg2= 2; 

    var results = RunPowerShellFunction("My-Function", parameters); 
    var obj = results[0]; 
    var str = results[1]; 
} 

private static dynamic RunPowerShellFunction(string functionName, dynamic parameters) 
{ 
    dynamic rv = null; 

    try 
    { 
     InitialSessionState iss = InitialSessionState.CreateDefault(); 

     using (Runspace runspace = RunspaceFactory.CreateRunspace(iss)) 
     { 
      runspace.Name = typeof(DockerManager).Name; 
      runspace.Open(); 

      RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace); 
      runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted"); 

      using (var mainPowerShell = System.Management.Automation.PowerShell.Create()) 
      { 
       mainPowerShell.Runspace = runspace; 

       mainPowerShell.AddScript(LoadedScriptText, false); 
       mainPowerShell.Invoke(); 

       var cmd = mainPowerShell.AddCommand(functionName); 

       if (parameters != null) 
       { 
        foreach (var parameter in parameters) 
        { 
         cmd.AddParameter(parameter.Key, parameter.Value); 
        } 
       } 

       rv = cmd.Invoke(); 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     Debug.WriteLine(ex.Message); 
    } 

    return rv; 
} 
관련 문제