Home > IronPython > Embedding PowerShell 2 in IronPython

Embedding PowerShell 2 in IronPython

PowerShell 2 makes the process of embedding PowerShell scripts inside other languages quite a bit simpler than in previous versions:

import clr
from System.Management.Automation import PowerShell
with PowerShell.Create() as ps:
   script = ps.AddScript("param([System.String]$pname)\r\nGet-Process -name $pname")
   script.AddParameters({"pname" : "devenv"})
   output = [o.BaseObject for o in script.Invoke()]

# Now you can access the Process object returned from the PS script.
print output[0].VirtualMemorySize64

You should create the PowerShell instance within a “with” block to ensure it is properly disposed after use. To pass parameters into a PS script, you’ll need to make sure the script accepts a few named parameters using the PS param() statement. Then you create a dict() of the name value pairs and add it as the parameters to the script. A Python list comprehension makes quick work of unwrapping the CLR objects from the PS output collection.

Categories: IronPython Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: