【问题标题】:Cannot invoke this function because the current host does not implement it无法调用此函数,因为当前主机没有实现它
【发布时间】:2013-01-31 16:39:01
【问题描述】:

我正在尝试从 c# 程序执行 PowerShell 命令并遇到“无法调用函数,因为当前主机未实现它”异常。

我正在尝试从 c# 程序执行 PowerShell 命令并遇到“无法调用函数,因为当前主机未实现它”异常。

这是我正在执行的……

public string RunScript(string cmd)
{
var initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new[] { @"C:\Intellitrace\Microsoft.VisualStudio.IntelliTrace.PowerShell.dll" });
var runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();
RunspaceInvoke invoker = new RunspaceInvoke(runspace);

// results =
invoker.Invoke(
@"Start-IntelliTraceCollection ""DefaultAppPool"" C:\Intellitrace\collection_plan.ASP.NET.trace.xml C:\IntellitraceLogs");

命令 Start-IntelliTraceCollection 在 IIS 检测期间使用 Cmdlet.Write* 写入详细日志,我猜这是导致异常的 write-host 的工作方式。此链接How to run PowerShell scripts via automation without running into Host issues 似乎建议创建一个写入主机函数并将其注入运行空间或在应用程序中实现 powershell 托管接口。任何关于如何做到这一点的代码示例都会非常有帮助。

我在这里提到了一个类似的问题Running a powershell command in C# errors with, "Cannot invoke this function because the current host does not implement it",它建议使用-Confirm:$false -Force,但我有兴趣了解如何通过实现 PSHost、PSHostUserInterface 和 PSHostRawUserInterface 来解决这个问题。如果有人可以提供有关如何完成此操作的代码示例,那将非常有用。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您在创建自定义主机(在 PSHostUserInterface 接口中)时提供实现的方法之一是

        Public Sub WriteVerboseLine(message As String)
    

    由于您没有提供主机(它又可以提供 PSHostUserInterface),因此您还没有告诉它如何处理 write-verbose 调用。

    这有意义吗?

    【讨论】:

      【解决方案2】:

      使用“write-host”会导致我出现此错误。直接在 qoutes 中输入你想要的任何内容,而不是“write-host”为我修复它。

      例如:而不是

      write-host 'ERROR! There is no free space for the selected category.'
      

      我用

      "ERROR! There is no free space for the selected category."
      

      注意:我的 senario 正在从 c# 的文本文件中调用 powershell 脚本

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-05-12
        • 2021-01-29
        • 2021-12-01
        • 1970-01-01
        • 2021-11-16
        • 2015-12-23
        • 2011-11-24
        相关资源
        最近更新 更多