【问题标题】:Using C# to execute PowerShell script with command line args using V2 methods使用 C# 使用 V2 方法执行带有命令行参数的 PowerShell 脚本
【发布时间】:2013-07-25 21:55:51
【问题描述】:

我正在编写一个 C# 应用程序,它需要使用命令行参数执行 Powershell 脚本并检索输出(也就是我希望在 PowerShell ISE 的输出窗口中看到的内容 - 包括异常信息)

我找到了许多关于如何使用 PowerShell V1 对象完成此任务的代码示例。这些示例创建运行空间、管道等(例如 Execute PowerShell Script from C# with Commandline Arguments

我看到很少有人提到使用 PowerShell V2 的不同方法。 (这里的最佳答案:Capturing Powershell output in C# after Pipeline.Invoke throws)使用 V2 似乎要简单得多。不要乱用运行空间、管道或任何其他东西。像这样的:

PowerShell powerShell = PowerShell.Create();

powerShell.AddScript(script);
var results = powerShell.Invoke();

有没有使用 PowerShell V2 对象从 C# 代码中执行脚本的好的工作示例?是否有任何已知的关于 PowerShell V2(甚至 V3)对象的良好文档以及如何使用它们的最佳实践?微软的官方文档应该有吗?一本很好的书或网站,可以逐个分解 System.Management.Automation 程序集?

【问题讨论】:

    标签: c# powershell powershell-2.0


    【解决方案1】:

    在这里回答我自己的问题。看起来正确的方法是让我的应用程序充当 PowerShell 主机

    https://msdn.microsoft.com/en-us/library/ee706563(v=vs.85).aspx

    此处定义了 PowerShell V2 对象的使用: http://msdn.microsoft.com/en-us/library/windows/desktop/system.management.automation.powershell(v=vs.85).aspx

    【讨论】:

      猜你喜欢
      • 2010-10-06
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      • 2021-10-11
      相关资源
      最近更新 更多