2016-04-23 152 views
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; 
    } 
} 

这是我的类库。当我第一次按下按钮时,我的脚本运行良好,但再次按下它会引发异常:从Windows窗体应用程序运行PowerShell脚本时出错

由于当前主机没有实现它,因此无法调用此函数。

如果我删除了脚本执行过程中创建的文件夹日志,那么它再次正常工作。

我的脚本:

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

rmdir需要你删除文件夹,如果该文件夹不为空之前进行确认(您需要键入“Y”,然后回车)。这就是为什么你会得到一个异常,因为用户交互不被支持。

使用Remove-Item命令与-Recurse -Force参数可以静静地删除目录。尝试使用以下命令而不是rmdir/mkdir。

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

非常感谢。它适用于我,但它需要太多时间才能生成结果。有什么方法可以生成更快的结果吗? – jasmin

+0

恐怕它需要很长时间,一台我的机器的文件大约是60M,事件日志中有很多条目 – kennyzx

+0

,所以没有办法加快解决方案的速度?如果我想从用户给出的位置读取我的文件,那我该怎么办? – jasmin