【问题标题】:Difference Between Pipeline and PowerShell class in C#C# 中 Pipeline 和 PowerShell 类的区别
【发布时间】:2018-12-21 09:37:05
【问题描述】:

我想知道在C# 中使用Pipeline 类与PowerShell 类执行PowerShell 脚本的区别。

使用管道:

Pipeline pipe = runspace.CreatePipeline();

使用 PowerShell 类:

PowerShell ps = PowerShell.Create();

我们可以同时使用它们在 C# 中执行 PowerShell 脚本,但是它们之间有什么区别呢?

【问题讨论】:

    标签: c# powershell runspace


    【解决方案1】:

    注意:PowerShell SDK documentation 非常稀疏,因此以下是推测

    • PowerShell 类的一个实例是 runspace 的包装器,它是运行 PowerShell 会话的容器;它的.RunSpace 属性返回封闭的运行空间。

    • 您需要一个运行空间(RunSpace 实例)来创建和执行 管道 以执行任意 PowerShell 语句。

    • 要创建管道,您有两种选择:

      • 如果你有一个PowerShell 实例,你可以使用它的便捷方法,例如.AddScript()隐式创建一个管道。

      • 或者,使用运行空间的.CreatePipeline() 方法显式地创建和管理管道。

    简单地说:PowerShell 类的便捷方法允许更简单地创建和执行管道。

    请注意,两种方法都支持执行多个语句,包括命令(例如,cmdlet 调用)和表达式(例如,1 + 2)的任意组合。

    以下 sn-p 比较了两种方法(使用 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()
    

    我可能遗漏了一些微妙之处;如果有,请告诉我们。

    【讨论】:

      【解决方案2】:

      您应该阅读文档。 pipelinerunspace 的一个特征。 PowerShell.Create() 方法将创建一个 PowerShell 对象,这是一种包含所有内容的包装器。这两种方法都属于同一个 PowerShell SDK。

      Pipeline 用于运行命令,位于runspace 对象下方。

      更多

      Pipeline Class (msdn)

      PowerShell Class (msdn)

      【讨论】:

      • @mklement0 我已经更新了我的答案,但我对范式的理解是 PowerShell 类型是一种包装器并处理 runspace/pipeline setup/teardown 而其他方法(使用runspacefactoryRunspace.CreatePipeline 是您可以操作的低级细节。
      猜你喜欢
      • 2021-07-14
      • 1970-01-01
      • 2020-02-22
      • 2017-04-04
      • 2011-04-29
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多