IronPython整合Windows PowerShell

來源:互聯網
上載者:User

      Windows PowerShell 是微軟為 Windows 環境所開發的 shell 及指令碼語言技術,這項全新的技術提供了豐富的控制與自動化的系統管理能力;關於PowerShell參看易學易用的Windows PowerShell 。IronPython也是指令碼語言,兩種指令碼語言的聯姻可以解決Windows 系統管理的任務,是系統管理員的必備工具。這裡有一篇文章在提醒DBA們要開始學PowerShell   RTFM :http://weblog.infoworld.com/dbunderground/archives/2007/01/rtfm.html

     PowerShell託管的API為IronPython整合PowerShell提供了條件。可以在IronPython直接存取PowerShell,直接利用PowerShell的強大Shell功能。下面的例子示範了IronPython中如何使用PowerShell。

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()
目錄: Microsoft.PowerShell.Core\FileSystem::D:\IronPython\Samples\IPPowerShel
l

Mode LastWriteTime Length Name
---- ------------- ------ ----
-ar-- 2006-9-14 14:46 3583 minsysreq.py
-ar-- 2006-9-14 14:44 3136 minsysreq_ps.py
-ar-- 2006-9-11 12:21 6261 powershell.py
-ar-- 2006-9-14 14:51 12911 readme.htm
>>> shell.dir().sort("LastWriteTime",Descending=True).select_object("Name")
Name
----
readme.htm
minsysreq.py
minsysreq_ps.py
powershell.py
>>>

例子代碼可以從這裡擷取:IronPython Sample ,有一個IPPowerShell例子,下載解壓後有一個IronPython script檔案powershell.py檔案。可以在通過在你的IronPython指令檔中通過使用這個powershell模組來使用PowerShell,當然你要安裝PowerShell。

下面我們來一起學習一下powershell.py檔案:

# **********************************************************************************
#
# 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 by
# 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 within
_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(_cmdName, _input=None, *args, **kws):
'''
Used to actually invoke a powershell command.
'''
#print 'invoke', _cmdName, _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 essentially has a method for
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['ToString'].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 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)

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裡面有幾個對象:RunSpace,PSMethod,PSObject等,具體可以參看PowerShell SDK。這個PowerShell模組對PowerShell對象進行了一個封裝成對象shell,這個對象封裝了PS的cmdlets 和aliases。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.