我想在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));
}
}
只是一個簡單的事情,但你可以通過簡單地使用'File.ReadAllText()'https://msdn.microsoft.com/en簡化'LoadScript' -us/library/ms143368(v = vs.110).aspx –