Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
when first time i pressed the button i works fine if i again pressed the button it will raise the exception
Cannot invoke this function because the current host does not implement it.
if i deleted the folder which is created during script execution then again it works
C#
ClasssLibrary1:Class
	Public 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();
   }
   
    public 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;
            }

        }

Here is my script to:
rmdir D:\Logs

mkdir D:\Logs

Get-EventLog Application |Format-List | Out-File D:\Logs\app.txt
Get-EventLog System |Format-List | Out-File D:\Logs\app.txt


What I have tried:

I added all the dll files of powershell to my project also manually added refernce to it using this:<reference include="System.Management.Automation">
Posted
Updated 23-Apr-16 4:39am
Comments
Sergey Alexandrovich Kryukov 23-Apr-16 16:45pm    
Why running a script from an application at all? It looks so weird that you need to provide some motivation, starting with explaining your ultimate goals.
—SA

1 solution

Quote:
if i deleted the folder which is created during script execution then again it works
Looks like rmdir D:\Logs is not working.
Did you check ?
Did you ensure the directory is empty before rmdir ?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900