从Windows表单应用程序运行PowerShell脚本时出错

时间:2016-04-23 13:31:43

标签: c# powershell powershell-v2.0

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

这是我的班级图书馆。当我第一次按下按钮时,我的脚本运行正常,但再次按下它会引发异常:

  

无法调用此函数,因为当前主机未实现它。

如果我删除了在脚本执行期间创建的文件夹Logs,那么它再次正常工作。

我的剧本:

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

1 个答案:

答案 0 :(得分:1)

如果文件夹不为空,则需要您在删除文件夹之前确认

<head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> </head> <body> <!-- html code ...--> </body> (您需要输入&#39; Y&#39;然后输入)。这就是为什么你得到一个例外,因为不支持用户交互。

使用带有rmdir参数的Remove-Item命令可以静默删除目录。尝试使用以下命令而不是rmdir / mkdir。

-Recurse -Force