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

Question:

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

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?

Answer:

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.

Source:

How to run PowerShell scripts via automation without running into Host issues by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply