none
PowerShell file executing using C# RRS feed

  • Question

  • Hi, 

    We are trying with C# code( using Visual WebPart) to execute a PowerShell file. I am getting the below error.

    A command that prompts the user failed because the host program or the command type does not support user interaction.

    Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows”

    Code

                string psScript = string.Empty;

                    if (File.Exists(strPsFile))

                        psScript = File.ReadAllText(strPsFile);

                    else

                        throw new FileNotFoundException("Wrong path for the script file");

                         Runspace runspace = RunspaceFactory.CreateRunspace();

                           runspace.Open();

                                       

                           RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);

                           runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");

                                        PowerShell psExec = PowerShell.Create();

                           psExec.AddScript(psScript);

                       Collection<PSObject> results;

                      Collection<ErrorRecord> errors;

                     results = psExec.Invoke();

                     errors = psExec.Streams.Error.ReadAll();

                    runspace.Close();

                    StringBuilder stringBuilder = new StringBuilder();

                    if (errors.Count > 0)

                    {

                        foreach (ErrorRecord error in errors)

                        {

                            stringBuilder.AppendLine(error.ToString());

                        }

                    }

                    else

                    {

                        foreach (PSObject obj in results)

                        {

                            stringBuilder.AppendLine(obj.ToString());

                        }

                    }

     

    Please share your thoughts on above issue.

    Regards,

    Sudheer


    Thanks & Regards, Sudheer

    Thursday, April 13, 2017 5:57 AM

Answers