问题描述
我希望通过自动化运行一些 powershell 脚本.类似的东西:
I'm looking to run some powershell scripts via automation. Something like:
IList errors;
Collection<PSObject> res = null;
using (RunspaceInvoke rsi = new RunspaceInvoke())
{
try
{
res = rsi.Invoke(commandline, null, out errors);
}
catch (Exception ex)
{
LastErrorMessage = ex.ToString();
Debug.WriteLine(LastErrorMessage);
return 1;
}
}
我面临的问题是,如果我的脚本使用诸如 write-host
之类的 cmdlet,上面会抛出一个 System.Management.Automation.CmdletInvocationException
-
the problem I'm facing is that if my script uses cmdlets such as write-host
the above throws an System.Management.Automation.CmdletInvocationException
-
无法调用这个函数,因为当前主机未实现
有哪些好的方法可以解决这个问题?
What are some good options for getting around this problem?
推荐答案
一种选择是创建一个写主机函数并将其注入到您的运行空间中.该函数将优先于具有相同名称的 cmdlet.在此函数中,如果您的应用程序是控制台应用程序,或者如果您的应用程序是 GUI 应用程序,则您可以什么都不做,或者使用 [console]::writeline() 将一些对象注入到函数可以写入输出的 PowerShell 会话中到(查看 Runspace.SessionStateProxy.SetVariable).
One option is to create a write-host function and inject that into your runspace. The function will take precedence over a cmdlet with the same name. In this function, you could do nothing or perhaps use [console]::writeline() if your app is a console app, or if your app is a GUI app, inject some object into the PowerShell session that the function can write the output to (look at Runspace.SessionStateProxy.SetVariable).
另一个(稍微复杂一点)选项是实现 应用程序中的 PowerShell 托管接口.
Another (bit more complicated) option is to implement the PowerShell hosting interfaces in your app.
这篇关于如何通过自动化运行 PowerShell 脚本而不会遇到主机问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!