使用 C# 使用 V2 方法通过命令行参数执行 PowerShell 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17867636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using C# to execute PowerShell script with command line args using V2 methods
提问by Derek Evermore
I am writing an C# application which will need to execute Powershell scripts with command line arguments and retrieve the output (aka what I would expect to see in the output window of PowerShell ISE - including exception information)
我正在编写一个 C# 应用程序,它需要使用命令行参数执行 Powershell 脚本并检索输出(也就是我希望在 PowerShell ISE 的输出窗口中看到的内容 - 包括异常信息)
I have found numerous code examples of how to accomplish this task using PowerShell V1 objects. These examples create runspaces, pipelines, etc. (ex Execute PowerShell Script from C# with Commandline Arguments)
我找到了许多关于如何使用 PowerShell V1 对象完成此任务的代码示例。这些示例创建运行空间、管道等(例如使用命令行参数从 C# 执行 PowerShell 脚本)
I have seen a few scant references to a different way to do this using PowerShell V2. (the top answer here: Capturing Powershell output in C# after Pipeline.Invoke throws) Using V2 seems muchsimpler. No messing around with runspaces, piplines or any of that. Something like this:
我已经看到了一些很少提及使用 PowerShell V2 执行此操作的不同方法。(此处的最佳答案:在 Pipeline.Invoke throws 之后在 C# 中捕获 Powershell 输出)使用 V2 似乎要简单得多。不要乱搞运行空间、管道或任何其他东西。像这样的东西:
PowerShell powerShell = PowerShell.Create();
powerShell.AddScript(script);
var results = powerShell.Invoke();
Are there any good working examples out there of using PowerShell V2 objects to execute scripts from within C# code? Is there any known good documentation of the PowerShell V2 (or even V3) objects and best practices on how to use them? Offical docs from Microsoft like there ought to be? A good book or site which breaks down the System.Management.Automation assembly piece by piece?
是否有使用 PowerShell V2 对象从 C# 代码中执行脚本的好的工作示例?是否有任何已知的 PowerShell V2(甚至 V3)对象的良好文档以及有关如何使用它们的最佳实践?微软的官方文档应该有吗?一本将 System.Management.Automation 组件逐一分解的好书或网站?
采纳答案by Derek Evermore
Answering my own question here. It looks like the right approach would be for my application to function as a PowerShell Host
在这里回答我自己的问题。看起来正确的方法是让我的应用程序充当 PowerShell 主机
https://msdn.microsoft.com/en-us/library/ee706563(v=vs.85).aspx
https://msdn.microsoft.com/en-us/library/ee706563(v=vs.85).aspx
Use of PowerShell V2 objects is defined here: http://msdn.microsoft.com/en-us/library/windows/desktop/system.management.automation.powershell(v=vs.85).aspx
PowerShell V2 对象的使用在此处定义:http: //msdn.microsoft.com/en-us/library/windows/desktop/system.management.automation.powershell(v= vs.85).aspx