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.
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.