[英]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;
}
}
这是我的班级图书馆。 当我第一次按下按钮时,我的脚本运行良好,但是再次按下它会引发异常:
由于当前主机未实现此功能,因此无法调用此功能。
如果我删除了在脚本执行过程中创建的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
如果文件夹不为空,则rmdir
需要在删除文件夹之前进行确认(您需要键入“ Y”,然后按Enter)。 这就是为什么出现异常的原因,因为不支持用户交互。
将Remove-Item
命令与-Recurse -Force
参数可以静默删除目录。 尝试使用以下命令代替rmdir / mkdir。
Remove-Item D:\Logs -Recurse -Force
New-Item -ItemType directory -Path D:\Logs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.