1

I am trying to execute a PowerShell script in C#, but I get a ParameterBindingException and I am pretty much stack.

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

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Dragomir
  • 13
  • 2
  • Just a simple thing, but you can simplify `LoadScript` by simply using `File.ReadAllText()` https://msdn.microsoft.com/en-us/library/ms143368(v=vs.110).aspx – Berin Loritsch May 03 '16 at 12:53

1 Answers1

0

I am sure that this happens due to wrong cmdlets being tried for execution. It has nothing to do with the c# code.

Inspect the value in the ScriptText variable being passed for execution to the RunScript method. Check the contents of that variable only and not the file contents, as they might be getting changed in the code. Copy it and try to execute in PowerShell. You will receive the same error.

Resolution: Correct the error in PowerShell. Add line breaks and propper pipeline where required. Then implement the same edit in the C#.

Check this post: Earlier SO post 1

Post 2

Community
  • 1
  • 1
Aman Sharma
  • 1,930
  • 1
  • 17
  • 31