7

I'm looking to run some powershell scripts via automation. Something like:

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;
    }
}

the problem I'm facing is that if my script uses cmdlets such as write-host the above throws an System.Management.Automation.CmdletInvocationException -

Cannot invoke this function because the current host does not implement it.

What are some good options for getting around this problem?

Scott Weinstein
  • 18,890
  • 14
  • 78
  • 115
  • Scott, I'm facing the same problem. Could you provide some guidance or code on how you did the implementation? – Markus Bruckner Nov 14 '10 at 22:24
  • Ok, found the answer myself: Just inherit PSHost, PSHostUserInterface and PSHostRawUserInterface and have the methods do nothing/return null. To trace what would normally happen, messages/text that would otherwise be printed at the cmd-line could be logged. – Markus Bruckner Nov 15 '10 at 15:35

1 Answers1

11

One option is to create a write-host function and inject that into your runspace. The function will take precedence over a cmdlet with the same name. In this function, you could do nothing or perhaps use [console]::writeline() if your app is a console app, or if your app is a GUI app, inject some object into the PowerShell session that the function can write the output to (look at Runspace.SessionStateProxy.SetVariable).

Another (bit more complicated) option is to implement the PowerShell hosting interfaces in your app.

Keith Hill
  • 194,368
  • 42
  • 353
  • 369