Windows powershell is a shell and script language technology developed by Microsoft for the Windows environment. This new technology provides rich control and automated system management capabilities; for more information about powershell, see the easy-to-use Windows powershell. Ironpython is also a scripting language. The combination of the two scripting languages can solve Windows system management tasks and is a necessary tool for system administrators. Here is an articleArticleReminding DBAs to start learning powershell rtfm: http://weblog.infoworld.com/dbunderground/archives/2007/01/rtfm.html
Powershell-hosted APIs provide conditions for ironpython to integrate powershell. You can directly access powershell in ironpython and directly use the powerful shell function of powershell. The following example demonstrates how to use powershell in ironpython.
D: \ ironpython \ samples \ ippowershell> IPY-I powershell. py
Run 'dir (Shell) 'to get a list of available powershell commands!
In general, ironpython powershell commands are accessed using the form:
Shell. get_process ("cmd"). Select (first = 2)
>>> Shell. dir ()
Directory: Microsoft. powershell. Core \ FileSystem: D: \ ironpython \ samples \ ippowershel
L
Mode lastwritetime length name
---------------------------
-Ar -- 3583 minsysreq. py
-Ar -- 3136 minsysreq_ps.py
-Ar -- 6261 powershell. py
-Ar -- 12911 readme.htm
>>> Shell. dir (). Sort ("lastwritetime", descending = true). select_object ("name ")
Name
----
Readme.htm
Minsysreq. py
Minsysreq_ps.py
Powershell. py
>>>
ExampleCodeYou can obtain the ironpython sample from here. There is an ippowershell example. After downloading and unzipping, there is an ironpython script file powershell. py. You can use powershell by using this powershell module in your ironpython script file. Of course you need to install powershell.
Next let's take a look at the powershell. py file:
#*************************************** **************************************** ***
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the shared source license
# For ironpython. A copy of the license can be found in the license.html File
# At the root of this distribution. If you can not locate the shared source license
# For ironpython, please send an email to ironpy@microsoft.com.
# By using this source code in any fashion, you are agreeing to be bound
# The terms of the shared source license for ironpython.
#
# You must not remove this notice, or any other, from this software.
#
#*************************************** **************************************** ***
Import CLR
CLR. addreference ('System. Management. Automation ')
CLR. addreference ('ironpython ')
From system. Management. Automation import *
From system. Management. Automation. Host import *
From system. Management. Automation. runspaces import *
Import System
# Create a new runspace to execute powershell commands
_ Runspace = runspacefactory. createrunspace ()
_ Runspace. open ()
_ Intrinsics = _ runspace. sessionstateproxy. getvariable ("executioncontext ")
Def translate (name ):
'''
Utility function converts a string, name, to lowercase.
Also replaces hyphens with underscores.
'''
Name = Name. Lower ()
Return name. Replace ('-','_')
Def fix_arg (ARG ):
'''
Utility function converts Arg (of Type string, psobjectwrapper, or
Shelloutput) to type string.
'''
If isinstance (ARG, STR ):
Arg = _ intrinsics. invokecommand. expandstring (ARG)
Elif isinstance (ARG, psobjectwrapper ):
Arg = Arg. Data
Elif isinstance (ARG, shelloutput ):
Arg = Arg. Data
Return ARG
Def invokecommand (_ parameter name, _ INPUT = none, * ARGs, ** KWS ):
'''
Used to actually invoke a powershell command.
'''
# Print 'invoke', _ callback name, _ INPUT
Cmd = command (_ cmdname)
# Adds parameters to the command
For ARG in ARGs:
Cmd. Parameters. Add (commandparameter (none, fix_arg (ARG )))
For name, value in KWS. Items ():
Cmd. Parameters. Add (commandparameter (name, fix_arg (value )))
# Create a pipeline to run the command within and invoke
# The command.
Pipeline = _ runspace. createpipeline ()
Pipeline. commands. Add (CMD)
If _ input:
Ret = pipeline. Invoke (fix_arg (_ INPUT ))
Else:
Ret = pipeline. Invoke ()
# Return the output of the command formatted special
# Using the shelloutput class
Return shelloutput (RET)
Class shell:
'''
Instances of this class are like pseudo powershell
Shells. That is, this class essential has a method
Each powershell command available.
'''
Def _ init _ (self, data ):
'''
Standard constructor. Just copies a dictionary Mapping
Powershell commands to names as members of this class.
'''
For key, value in data. Items ():
Setattr (self, key, value)
Class shellcommand (object ):
'''
Wrapper class for shell commands.
'''
Def _ init _ (self, name, input = none ):
'''
'''
Self. Name = Name
Self. Input = Input
Def _ call _ (self, * ARGs, ** KWS ):
'''
'''
Return invokecommand (self. Name, self. Input, * ARGs, ** KWS)
Def _ GET _ (self, instance, context = none ):
'''
'''
Return shellcommand (self. Name, instance)
Def _ repr _ (Self ):
'''
'''
Return "<shellcommand % S>" % self. Name
Class shelloutput (object ):
'''
'''
Def _ init _ (self, data ):
'''
'''
Self. Data = Data
Def _ Len _ (Self ):
'''
'''
Return self. Data. Count
Def _ repr _ (Self ):
'''
'''
If self. Data. Count = 0: Return''
Return STR (self. out_string (width = system. Console. BufferWidth-1) [0]). Strip ()
Def _ getitem _ (self, index ):
'''
'''
If index> = self. Data. Count: Raise indexerror
Ret = self. Data [Index]
If isinstance (Ret, psobject ):
Return psobjectwrapper (RET)
Class psobjectwrapper (object ):
'''
'''
Def _ init _ (self, data ):
'''
'''
Self. Data = Data
Def _ getattr _ (self, name ):
'''
'''
Member = self. Data. members [name]
If member is not none:
Ret = member. Value
If isinstance (Ret, psmethod ):
Ret = invoketocallableadapter (RET)
Return ret
Raise attributeerror (name)
Def _ repr _ (Self ):
'''
'''
Return self. Data. members ['string']. Invoke ()
Def dump (o ):
'''
'''
Print STR (O. out_string (width = system. Console. BufferWidth-1) [0]). Strip ()
Class invoketocallableadapter:
'''
'''
Def _ init _ (self, meth ):
'''
'''
Self. Meth = meth
Def _ call _ (self, * ARGs ):
'''
'''
Return self. Meth. Invoke (* ARGs)
Def init_runspace ():
'''
'''
Global Shell
# Build up a dictionary of native powershell commands where
# Each value consists of the ps command wrapped
# 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 '):
CommonName = translate (alias. referencedcommand. Name)
If your name in cmds:
Cmds [translate (alias. Name)] = cmds [alias name]
Shell = shell (cmds)
Shelloutput. _ dict _. Update (cmds)
Init_runspace ()
If _ name _ = '_ main __':
Print "" Run \ 'dir (Shell) \ 'to get a list of available powershell commands!
In general, ironpython powershell commands are accessed using the form:
Shell. get_process ("cmd"). Select (first = 2)
"""
Powershell contains several objects: runspace, psmethod, psobject, etc. For details, see powershell SDK. This powershell module encapsulates powershell objects into an object shell, which encapsulates PS cmdlets and aliases.