Powershell簡介及其編程訪問

作者: 陳希章  來源: 博客園  發布時間: 2010-10-17 22:35  閱讀: 1968 次  推薦: 0   原文鏈接   [收藏]  
摘要:Powershell是下一代的命令行外殼程序,較之于它的前身(cmd.exe),它的功能更加強大,也更加易用。最根本的區別在于它是基于對象的操作(基于.NET Framework),而不是基于字符串的操作。

  這個工具可以單獨使用,完全可以取代cmd.exe。例如如下:

image  但它的功能遠不止于此,例如我們可以很容易地獲取所有的進程名稱:

image  再來看一個,下面這個例子是獲取當前正在運行的服務列表。(可以用條件很方便地篩選):

image  除此之外,Powershell還支持定制,例如微軟很多產品都提供了專門的Powershell插件(典型的有:SQL Server,SharePoint Server, Exchange Server等)。通過這些特殊的外殼,可以實現對服務器的管理。功能非常強大。例如下面的SQLPS,可以像查看文件夾那樣查看數據庫:

image  再例如下圖的EMS(Exchange Managment Shell),可以對一個地址列表進行修改:

image  看起來還不錯吧,關于Powershell的更多細節,大家有興趣的話,可以參考微軟有關的文檔。接下來談另外一個話題,Powershell這么強大,但終究是手工地操作,能不能在程序中調用它,并且執行有關的操作呢?

答案是:可以的。下面我們來看一個小的例子:

image  添加一個引用。這個程序集在C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0目錄中:

image  編寫如下簡單的代碼:

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Diagnostics;

namespace PowershellInvoker
{

class Program
{

static void Main(string[] args)
{
var runspace
= RunspaceFactory.CreateRunspace();
runspace.Open();

var piple
= runspace.CreatePipeline("Get-Process");
var result
= piple.Invoke().Select(p => p.BaseObject).Cast<Process>();

foreach (var item in result)
{
Console.WriteLine(
"{0}\t{1}\t{2}",
item.Id.ToString().PadRight(
30),
item.ProcessName.PadRight(
30),
item.Threads.Count);


}

Console.Read();
}
}
}

image  是的,Powershell據是基于.NET Framework的對象操作。

0
0
 
標簽:Powershell
 
 

文章列表

全站熱搜
創作者介紹
創作者 大師兄 的頭像
大師兄

IT工程師數位筆記本

大師兄 發表在 痞客邦 留言(0) 人氣()