Thursday, February 21, 2008

Embedding PowerShell in IronPython and vice versa -- “two great tastes that taste great together”

PowerShell and Python may both be scripting languages, but their strengths are in different areas. One place where PowerShell excels is in getting prettily formatted text output out of your windows system calls, and making a lot of standard queries without having to go to all the hassle that diving into the System.Management namespace often involves (writing your own WQL queries and the like).

So, why not embed the one script inside the other?

In the example, we get a single pretty-printed list of all the processes. If we hadn't added the Out-String, we would have a collection of System.Diagnostics.Process objects that we could work with as .Net objects in their own right. And objects can be passed in via runspace.SessionStateProxy.SetVariable("variableName", theObject) and picked up as $variableName in the PowerShell script.

As IronPython can be embedded in .Net, it can of course be embedded in PowerShell, like this (for 1.x)

The 2.0 code is similar in spirit, but different in detail:

H/t CodeProject

1 comment :

David Seruyange said...

I'd experimented with something like this (check and had some limited success. I'll see if I can get it to work with the approach you are using. I had a hard time keeping a "context" with the shell versus just a command at a time.