2

I am trying to execute a PowerShell command from a c# program and running into the “Cannot invoke the function because the current host does not implement it” exception.

Screenshot

I am trying to execute a PowerShell command from a c# program and running into the “Cannot invoke the function because the current host does not implement it” exception.

Here is what I am executing…

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");

The command Start-IntelliTraceCollection writes a verbose log using Cmdlet.Write* during IIS instrumentation, I guess it’s the way write-host works which is causing the exception. This link here, How to run PowerShell scripts via automation without running into Host issues, seems to recommend creating a write host function and injecting that into the runspace or implement the powershell hosting interface in the app. Any code samples on how this can be done would be very helpful.

I have refereed to a similar question here Running a powershell command in C# errors with, "Cannot invoke this function because the current host does not implement it" which suggests using -Confirm:$false -Force but I am interested in seeing how this can be fixed by implementing the PSHost, PSHostUserInterface and PSHostRawUserInterface. It would be very useful if any one can provide a code sample on how this can be done.

Community
  • 1
  • 1
Tarun Arora
  • 4,692
  • 4
  • 30
  • 40

2 Answers2

1

One of the methods that you provide an implementation for when creating a custom host (in the PSHostUserInterface interface) is

    Public Sub WriteVerboseLine(message As String)

Since you haven't provided a host (which in turn can provide a PSHostUserInterface), you haven't told it what to do with a write-verbose call.

Does that make sense?

Mike Shepard
  • 17,466
  • 6
  • 51
  • 69
0

using "write-host" causes me this error. just directly type whatever you want in qoutes instead of "write-host" fixes it for me.

eg : instead of

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

i use

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

Note: my senario is calling powershell script in text file from c#

Ram
  • 15,908
  • 4
  • 48
  • 41