除了作为一种脚本语言外,Windows PowerShell被多种应用程序使用。这是因为Windows PowerShell引擎可以被托管在一个应用程序内部。这篇博文和下一篇博文将会处理在C#应用程序中托管Windows Powershell的多个API.

用来托管Windows Powershell最为重要的一个类型是System.Management.Automation.PowerShell类。这个类提供了用来创建命令管道和在运行空间中执行命令的方法。

添加命令(AddCommand)

让我们来看一个非常简单的例子。假设你想得到当前机器上运行的进程的一个列表。执行命令的方式如下。

步骤 1 – 创建一个 PowerShell 对象

1
PowerShell ps = [PowerShell]::Create();

步骤 2 – 添加你想执行的命令

1
ps.AddCommand(“Get-Process”);

步骤 3 –执行这些命令

1
ps.Invoke();

你也可以像这样一步到位执行这些步骤:

1
[PowerShell]::Create().AddCommand(“Get-Process”).Invoke();

添加参数(AddParameter)

上面执行单个命令的例子没有任何参数。比方说,我想得到运行在当前机器上的所有PowerShell进程。我就可以使用AddParamete方法来给命令添加参数了。

1
2
3
[PowerShell]::Create().AddCommand(“Get-Process”)
                   .AddParameter(“Name”, “PowerShell”)
                   .Invoke();

如果想添加更多参数,可以像这样继续调用:

1
2
3
4
[PowerShell]::Create().AddCommand(“Get-Process”)
                   .AddParameter(“Name”, “PowerShell”)
                   .AddParameter(“Id”, “12768”)
                   .Invoke();

或者,如果你有一个包含参数名和参数的词典,可以使用AddParameters ,来添加所有参数。

1
2
3
4
5
6
IDictionary parameters = new Dictionary<String, String>();
parameters.Add("Name""PowerShell");
parameters.Add("Id""12768");
[PowerShell]::Create().AddCommand(“Get-Process”)
           .AddParameters(parameters)
           .Invoke()

添加语句(AddStatement)

现在我们已经执行了一个单独的命令和它的参数,让我们再来执行一堆命令。PowerShell API给我们提供了一个模拟批处理的方式,这样就可以在管道的末尾追加额外的语句。获取所有正在运行的进程,然后再获取所有正在运行的服务,可以这样做:

1
2
3
4
PowerShell ps = [PowerShell]::Create();
ps.AddCommand(“Get-Process”).AddParameter(“Name”, “PowerShell”);
ps.AddStatement().AddCommand(“Get-Service”);
ps.Invoke();

添加脚本(AddScript)

AddCommand方法只能添加命令。如果我想运行一个脚本,我可以使用 AddScript 方法。假设我们有一个简单的脚本,a.ps1,可以获取机器上所有运行的PowerShell进程的的数量。

1
2
3
4
5
6
------------D:\PshTemp\a.ps1----------
$a Get-Process -Name PowerShell
$a.count
------------D:\PshTemp\a.ps1----------
PowerShell ps = [PowerShell]::Create();
ps.AddScript(“D:\PshTemp\a.ps1”).Invoke();

AddScript API也提供了一个选项来在本地作用域运行脚本。在下面的例子中,脚本会在本地作用域中来执行,因为我们将true传递给了参数useLocalScope 。

1
2
PowerShell ps = [PowerShell]::Create();
ps.AddScript(@“D:\PshTemp\a.ps1”, true).Invoke();

处理错误,详细消息,警告和进度信息(Handling Errors, Verbose, Warning, Debug and Progress Messages)

PowerShell API也能让我们访问命令运行时产生的错误和详细信息等。你可以使用PowerShell.Streams.Error属性获取错误信息,和PowerShell.Streams.Verbose 属性获取详细信息。下面的属性也可以获取进度,调试,和警告信息。

1
2
3
4
PowerShell ps = [PowerShell]::Create()
                          .AddCommand("Get-Process")
                          .AddParameter("Name""Non-ExistentProcess");
ps.Invoke();

ps.Streams.Error有一个命令运行时产生的错误列表,下面的情况,我们在查询一个不存在的进程时得到了一个错误

1
2
3
4
5
6
Get-Process : Cannot find a process with the name "Non-ExistentProcess".
Verify the process name and call the cmdlet again.
+ CategoryInfo : ObjectNotFound: (Non-ExistentProcess:String) [Get-Process],
ProcessCommandException
+ FullyQualifiedErrorId :
NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand

PowerShell API 非常强大。它能让我们在同步/异步模式下运行命令,创建一个只能运行有限命令集的受约束的运行空间,在嵌套的管道中执行命令,等等。

在本文中的所有例子中,我们创建了一个包含了所有Windows PowerShell 内置命令的默认运行空间,这在内存消耗方面并不高效。在更多的场景中,用户可能想创建一个只包含指定命令集/语言元素的运行空间。在下一篇博文中,我们会解释如何创建一个受限制但是效率更高的运行空间。

Original Author: Indhu Sivaramakrishnan [MSFT] (Windows PowerShell Developer)

From:http://www.pstips.net/paap-windows-powershell-as-a-platform-part-1.html

      http://blogs.msdn.com/b/powershell/archive/2013/10/01/paap-windows-powershell-as-a-platform-part-1.aspx

作为平台的Windows PowerShell(一)的更多相关文章

  1. 作为平台的Windows PowerShell(二)

    在此系列文章的前一篇,我们看到了怎样使用System.Management.Automation.PowerShell 类来在c#应用程序中运行PowerShell 命令.在那些例子中,我们创建的都是 ...

  2. SharePoint 2010 最佳实践学习总结------第2章 SharePoint Windows PowerShell指南

    第2章 SharePoint Windows PowerShell指南 SharePoint 2010是SharePoint系列产品中第一个开始支持Windows PowerShell的产品,在以前的 ...

  3. 解决VS2015启动时Package manager console崩溃的问题 - Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope

    安装VS2015,启动以后,Package manager console崩溃,错误信息如下: Windows PowerShell updated your execution policy suc ...

  4. 用Windows PowerShell 控制管理 Microsoft Office 365

    如果想要通过PowerShell控制管理Office365,首先要安装Microsoft Online Services Sign-In Assistant 7.0,链接如下 Microsoft On ...

  5. 【SharePoint学习笔记】第2章 SharePoint Windows PowerShell 指南

    快速了解Windows PowerShell     从SharePoint 2010开始支持PowerShell,仍支持stsadm.exe工具:     可以调用.NET对象.COM对象.exe文 ...

  6. Office 365 - SharePoint 2013 Online 中使用Windows PowerShell

    1.如果想要在SharePoint Online中使用Windows PowerShell,首先需要安装SharePoint Online Management Shell(下载地址附后),如下图: ...

  7. 检测访问网页的浏览器呈现引擎、平台、Windows操作系统、移动设备和游戏系统

    /** * Author: laixiangran. * Created by laixiangran on 2015/12/02. * 检测访问网页的浏览器呈现引擎.平台.Windows操作系统.移 ...

  8. 使用 Windows PowerShell 来管理和开发 windowsazure.cn 账户的特别注意事项

    6月6日,微软面向中国大陆用户开放了Microsoft Azure公众预览版的申请界面.大家可以申请免费的 beta 试用,收到内附邀请码的通知邮件后只需输入激活码即可开始免费试用.具体网址为: ht ...

  9. Windows PowerShell ISE

    Windows PowerShell 集成脚本环境 (ISE) 是 Windows PowerShell 的主机应用程序.在 Windows PowerShell ISE 中,可以在单一 Window ...

随机推荐

  1. Target host is not specified错误

    对于httpClient4.3访问指定页面,可以从下面的demo抽取方法使用. 注意:对于URL必须使用 http://开始,否则会有如下报错信息: 或者在设置cookie时带上domain: coo ...

  2. Nhibernate与Dapper对比,及Nhibernate增删改和9种查询语法

    1,Sql语法. NH:HQL Dapper:原生Sql. 点评:原生Sql可以直接放在数据库里执行,Hql不行,且Hql增加学习负担.(Hn也可以原生Sql,但好像用的不多呀) 2,开发速度. NH ...

  3. Linux 根文件系统制作

    1.创建根文件目录 mkdir rootfs(名字是随便取的) 2.创建子目录 cd rootfs mkdir bin dev etc lib proc sbin sys usr mnt tmp va ...

  4. HDU 1532 Drainage Ditches 排水渠(最大流,入门)

    题意: 给出一个有向图,以及边上的容量上限,求最大流.(有重边,要将容量上限叠加) 思路: 用最简单的EK+BFS解决.每次搜到一条到达终点的路径,就立刻退出,更新ans,然后再回头修改图中的当前fl ...

  5. 【转】Android自定义View的实现方法,带你一步步深入了解View(四)

    原文网址: 转载请注明出处:http://blog.csdn.net/guolin_blog/article/details/17357967 不知不觉中,带你一步步深入了解View系列的文章已经写到 ...

  6. jquery放大镜

    效果体验:http://runjs.cn/detail/dvygyp5t demo下载 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Tra ...

  7. ToString() 格式化字符串

    例如i=: i.ToString().PadLeft(,'); 固定长度为10,左不足补0,结果为0000000001:

  8. Android调试工具及方法

    转自:http://www.cnblogs.com/feisky/archive/2010/01/01/1637566.html Logcat Dump一份系统消息的日志.这些消息包括模拟器抛出错误时 ...

  9. 【转】ExcelHelper类,用npoi读取Excel文档

    //------------------------------------------------------------------------------------- // All Right ...

  10. C/C++编译预处理命令详解【转】

    1.       预处理程序  按照ANSI标准的定义,预处理程序应该处理以下指令: #if #ifdef #ifndef #else #elif #endif #define #undef #lin ...