简体   繁体   中英

Error Running PowerShell Script From Windows form application

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;
    }
}

This is my class library. when first time i press the button my script runs fine but then again pressed it raise the exception:

Cannot invoke this function because the current host does not implement it.

If i deleted the folder Logs which is created during script execution then again it works fine.

My script:

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

rmdir needs you to confirm before deleting the folder if the folder is not empty (you need to type 'Y' and then Enter). And that is why you get an exception because user interaction is not supported.

Use the Remove-Item command with -Recurse -Force parameters can silently remove the directory. Try to use the following commands instead of rmdir/mkdir.

Remove-Item D:\Logs -Recurse -Force
New-Item -ItemType directory -Path D:\Logs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM