c# - C# 中 Pipeline 和 PowerShell 类的区别

标签 c# powershell runspace

我想知道使用 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/

相关文章:

c# - 如何避免表单数据中的 url 编码

powershell - 是否可以在 Powershell 中处理 Get-AzureManagedCache 异常?

powershell - Powershell:在命令行中调用Powershell时,如何传递变量以切换参数?

c# - 在运行空间中导入或加载模块,仍然 'Connect-AzureRMAccount' 抛出 'command not recognised as cmdlet..'

c# - 在运行时确定 C# P/Invoke 结构对齐

c# - 双缓冲在面板上不起作用?

c# - 在 C# 中使用 Powershell 远程调用的内存泄漏

c# - 使用 Uri 创建时,新 Runspace 对象的 SessionStateProxy 属性为空

c# using 语句放置

windows - 有什么办法可以使用Powershell在文件夹中找到 'metadata'