Adding Additional Snapins to IronPython

From IronPython Cookbook

Powershell can host other applications. Exchange 2007 is one of the first environments to fully take advantage of this with their snapins. By default, the powershell module supplied with ironpython does see other snapins. Here is a simple example that modifies init_runspace in powershell.py so that other snapins are available to ironpython.

I marked with comments the section that has new code. If you do not want to add all snapins, the code is easily customizable. With this change, ironpython on an exchange 2007 server will now have the exchange tools available to it.


def init_runspace():

    '''
    '''

    global shell

    #####START CODE to add all available snapins####    
    for snapin in InvokeCommand('Get-PsSnapin',registered=True):
        InvokeCommand('Add-PsSnapin',name=snapin.name)
    for cmdlet in InvokeCommand('get-command'):
        cmds[translate(cmdlet.Name)] = ShellCommand(cmdlet.Name)
    #####END CODE to add all available snapins####

    #build up a dictionary of native PowerShell commands where 
    #each value consists of the PS command wrapped within 
    #the ShellCommand helper class

    cmds = {}
    for cmdlet in InvokeCommand('get-command'):
        cmds[translate(cmdlet.Name)] = ShellCommand(cmdlet.Name)
	#look for all aliases and for each of them that map directly
	#into a native PowerShell command, support them directly
	#from the dictionary

    for alias in InvokeCommand('get-alias'):
        cmdName = translate(alias.ReferencedCommand.Name)
        if cmdName in cmds:
            cmds[translate(alias.Name)] = cmds[cmdName]

    shell = Shell(cmds)
    ShellOutput.__dict__.update(cmds)


Then you can do something like this. You may want to create a new module called powershell2 instead of modifying the original.

import powershell2
print powershell2.shell.get_mailbox()

Back to Contents.

TOOLBOX
LANGUAGES