我希望通过自动化运行一些 powershell 脚本。就像是:
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;
}
}
我面临的问题是,如果我的脚本使用 cmdlet,例如
write-host
以上抛出 System.Management.Automation.CmdletInvocationException
-Cannot invoke this function because the current host does not implement it.
有什么好的选择可以解决这个问题?
最佳答案
一种选择是创建一个 write-host 函数并将其注入(inject)您的运行空间。该函数将优先于具有相同名称的 cmdlet。在此函数中,如果您的应用程序是控制台应用程序,或者如果您的应用程序是 GUI 应用程序,您可以什么都不做,或者可能使用 [console]::writeline(),将一些对象注入(inject)到函数可以写入输出的 PowerShell session 中到(查看 Runspace.SessionStateProxy.SetVariable)。
另一个(稍微复杂一点)选项是实现 PowerShell hosting interfaces in your app .
关于powershell - 如何通过自动化运行 PowerShell 脚本而不会遇到主机问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2656610/