Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run PowerShell scripts via automation without running into Host issues

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?

like image 864
Scott Weinstein Avatar asked Apr 16 '10 23:04

Scott Weinstein


People also ask

Can we run PowerShell script in Automation Anywhere?

From what I can tell, the only way to invoke a PowerShell script is to use the "Open program/file" action to launch the PowerShell interpreter and to pass it the path to the script to execute.

How do I run a PowerShell script without the console?

run with a hidden window flag to launch cmd.exe /c powershel.exe -file c:\script. ps1. When powershell is called from cmd it will run in the existing cmd window which is already hidden by wscript.exe //b /nologo c:\launcher. vbs.


1 Answers

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.

like image 156
Keith Hill Avatar answered Nov 08 '22 08:11

Keith Hill