如何通过自动化运行PowerShell脚本而不会遇到Host问题

Sco*_*ein 7 powershell hosting automation powershell-2.0

我希望通过自动化运行一些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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我面临的问题是,如果我的脚本使用write-host如上所述的cmdlet 抛出System.Management.Automation.CmdletInvocationException-

无法调用此函数,因为当前主机未实现它.

有什么好方法可以解决这个问题?

Kei*_*ill 11

一种选择是创建一个写主机函数并将其注入您的运行空间.该函数将优先于具有相同名称的cmdlet.在此函数中,如果您的应用程序是控制台应用程序,或者如果您的应用程序是GUI应用程序,则无法执行任何操作或者可能使用[console] :: writeline(),将一些对象注入到PowerShell会话中,该函数可以编写输出to(查看Runspace.SessionStateProxy.SetVariable).

另一个(更复杂的)选项是在您的应用程序中实现PowerShell托管接口.