powershell - 如何通过自动化运行 PowerShell 脚本而不会遇到主机问题

标签 powershell automation hosting 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;
    }
}

我面临的问题是,如果我的脚本使用 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/

相关文章:

jsp - 网站所有者在更新网站时是否需要重新启动服务器?

powershell - 使用 Powershell 确定 Internet 连接

sharepoint - 批量复制文件到 SharePoint 站点

python-3.x - pywintypes.com_error : (-2147024882, 'Not enough memory resources are available to complete this operation.',无,无)

Spring 托管组合

c# - 服务器上的 DateTime.Now 问题

powershell - 为什么我不能将 PowerShell 的 Start-Process 与 -Credential 和 -Verb 参数一起使用?

regex - 正则表达式从字符串中提取某些位

azure - 在 Azure Devops 中使用 powershell 自动化 Connect-AzureAD

c# - 发送 Numpad 上的特定键,例如 +、- 或 Enter(模拟按键)