2016-05-03 87 views
1

我想在C#中執行一個PowerShell腳本,但我得到一個ParameterBindingException,我幾乎堆棧。執行在C#中的powershell

private string path = @"d:\\foo.ps1"; 

private string RunScript(string scriptText) 
{ 
    Runspace runspace = RunspaceFactory.CreateRunspace(); 

    runspace.Open(); 

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

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

    Collection<PSObject> results = pipeline.Invoke(); 

    runspace.Close(); 

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

    return stringBuilder.ToString(); 
} 

private string LoadScript(string filename) 
{ 
    try 
    { 
     using (StreamReader sr = new StreamReader(filename)) 
     { 
      StringBuilder fileContents = new StringBuilder(); 

      string curLine; 

      while ((curLine = sr.ReadLine()) != null) 
      { 
       fileContents.Append(curLine + "\n"); 
      } 

      return fileContents.ToString(); 
     } 
    } 
    catch (Exception e) 
    { 
     string errorText = "The file could not be read:"; 
     errorText += e.Message + "\n"; 
     return errorText; 
    } 
} 

private void button1_Click(object sender, EventArgs e) 
{ 
    RunScript(LoadScript(path)); 
} 
} 

enter image description here

+0

只是一個簡單的事情,但你可以通過簡單地使用'File.ReadAllText()'https://msdn.microsoft.com/en簡化'LoadScript' -us/library/ms143368(v = vs.110).aspx –

回答

0

我相信,出現這種情況是由於錯誤的cmdlet受審執行。它與C#代碼無關。

檢查要傳遞給RunScript方法的ScriptText變量中的值。僅檢查該變量的內容而不檢查文件內容,因爲它們可能在代碼中被更改。複製它並嘗試在PowerShell中執行。您將收到同樣的錯誤。

解決方案:更正PowerShell中的錯誤。根據需要添加換行符和propper管道。然後在C#中執行相同的編輯。

檢查這個帖子:Earlier SO post 1

Post 2

+0

真的爲你回答幫助我很多 – Dragomir

+0

@Dragomir我很高興它幫助。 –