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

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

really ty for u answer help me alot
@Dragomir I am glad it helped.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.