title: Cannot invoke this function because the current host does not implement it
body: <p>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.</p>
  
  <p><img src="https://i.stack.imgur.com/8ad6K.jpg" alt="Screenshot"></p>
  
  <p>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.</p>
  
  <p>Here is what I am executing…</p>
  
  <pre><code>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");
  </code></pre>
  
  <p>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, <a href="https://stackoverflow.com/questions/2656610/how-to-run-powershell-scripts-via-automation-without-running-into-host-issues">How to run PowerShell scripts via automation without running into Host issues</a>, 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.</p>
  
  <p>I have refereed to a similar question here <a href="https://stackoverflow.com/questions/4219095/running-a-powershell-command-in-c-sharp-errors-with-cannot-invoke-this-functio">Running a powershell command in C# errors with, &quot;Cannot invoke this function because the current host does not implement it&quot;</a> which suggests using <code>-Confirm:$false</code> -<code>Force</code> 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.  </p>