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
非常感谢。它适用于我,但它需要太多时间才能生成结果。有什么方法可以生成更快的结果吗? – jasmin
恐怕它需要很长时间,一台我的机器的文件大约是60M,事件日志中有很多条目 – kennyzx
,所以没有办法加快解决方案的速度?如果我想从用户给出的位置读取我的文件,那我该怎么办? – jasmin