我想知道使用 Pipeline
类与 PowerShell
类在 C#
中执行 PowerShell 脚本之间的区别。
使用管道:
Pipeline pipe = runspace.CreatePipeline();
使用 PowerShell 类:
PowerShell ps = PowerShell.Create();
我们都可以使用它们来执行C#中的PowerShell脚本,但是它们之间有什么区别呢?
最佳答案
注意:PowerShell SDK documentation非常稀疏,因此以下内容是推测性的。
PowerShell
的一个实例类是运行空间(PowerShell session 在其中运行的容器)的包装器;它的.RunSpace
属性返回封闭的运行空间。您需要一个运行空间(
RunSpace
实例)来创建和执行用于执行任意 PowerShell 语句的管道。要创建管道,您有两种选择:
如果您有
PowerShell
实例,则可以使用其便捷方法(例如.AddScript()
)隐式创建一个管道。或者,使用运行空间的
.CreatePipeline()
显式创建和管理管道的方法。
简单地说:PowerShell
类的便捷方法允许更简单地创建和执行管道。
请注意,两种方法都支持执行多个语句,包括命令(例如 cmdlet 调用)和表达式(例如1 + 2)的任意组合
).
以下代码片段比较了两种方法(使用 PowerShell 本身),据我所知,它们在功能上是等效的:
# Create a PowerShell instance and use .AddScript() to implicitly create
# a pipeline that executes arbitrary statements.
[powershell]::Create().AddScript('Get-Date -DisplayHint Date').Invoke()
# The more verbose equivalent using the PowerShell instance's .RunSpace
# property and the RunSpace.CreatePipeline() method.
[powershell]::Create().RunSpace.CreatePipeline('Get-Date -DisplayHint Date').Invoke()
我可能遗漏了一些微妙之处;如果是的话,请告诉我们。
关于c# - C# 中 Pipeline 和 PowerShell 类的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51317768/