来自 Windows 表单应用程序的错误 运行 PowerShell 脚本
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;
}
}
这是我的 class 图书馆。当我第一次按下按钮时,我的脚本运行正常,但再次按下它会引发异常:
Cannot invoke this function because the current host does not implement it.
如果我删除了在脚本执行期间创建的文件夹 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'然后回车)。这就是为什么会出现异常,因为不支持用户交互。
使用带-Recurse -Force
参数的Remove-Item
命令可以静默删除目录。尝试使用以下命令代替 rmdir/mkdir.
Remove-Item D:\Logs -Recurse -Force
New-Item -ItemType directory -Path D:\Logs
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;
}
}
这是我的 class 图书馆。当我第一次按下按钮时,我的脚本运行正常,但再次按下它会引发异常:
Cannot invoke this function because the current host does not implement it.
如果我删除了在脚本执行期间创建的文件夹 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'然后回车)。这就是为什么会出现异常,因为不支持用户交互。
使用带-Recurse -Force
参数的Remove-Item
命令可以静默删除目录。尝试使用以下命令代替 rmdir/mkdir.
Remove-Item D:\Logs -Recurse -Force
New-Item -ItemType directory -Path D:\Logs