Select-Object如何在PowerShell v3中停止管道?

时间:2012-01-05 20:21:49

标签: powershell powershell-v3.0

在PowerShell v2中,以下行:

1..3| foreach { Write-Host "Value : $_"; $_ }| select -First 1

会显示:

Value : 1
1
Value : 2
Value : 3

因为所有元素都被推下了管道。但是,在v3中,上面的行仅显示:

Value : 1
1

管道在2和3发送到Foreach-Object之前停止(注意:-Wait的{​​{1}}开关允许所有元素到达Select-Object块。< / p>

foreach如何停止管道,现在我可以从Select-Object或我自己的功能停止管道吗?

编辑:我知道我可以在do ... while循环中包装一个管道,然后继续管道。我还发现在v3中我可以做这样的事情(它在v2中不起作用):

foreach

但是function Start-Enumerate ($array) { do{ $array } while($false) } Start-Enumerate (1..3)| foreach {if($_ -ge 2){break};$_}; 'V2 Will Not Get Here' 不需要这些技术,所以我希望有一种方法可以从管道中的单个点停止管道。

3 个答案:

答案 0 :(得分:3)

查看此帖子,了解如何取消管道:
http://powershell.com/cs/blogs/tobias/archive/2010/01/01/cancelling-a-pipeline.aspx

在PowerShell 3.0中,这是一项引擎改进。从CTP1示例文件夹('\ Engines Demos \ Misc \ ConnectBugFixes.ps1'):

# Connect Bug 332685
# Select-Object optimization
# Submitted by Shay Levi
# Connect Suggestion 286219
# PSV2: Lazy pipeline - ability for cmdlets to say "NO MORE"
# Submitted by Karl Prosser

# Stop the pipeline once the objects have been selected
# Useful for commands that return a lot of objects, like dealing with the event log

# In PS 2.0, this took a long time even though we only wanted the first 10 events
Start-Process powershell.exe -Args '-Version 2 -NoExit -Command Get-WinEvent | Select-Object -First 10'

# In PS 3.0, the pipeline stops after retrieving the first 10 objects
Get-WinEvent | Select-Object -First 10

答案 1 :(得分:3)

尝试了几种方法,包括抛出StopUpstreamCommandsException,ActionPreferenceStopException和PipelineClosedException,调用$ PSCmdlet.ThrowTerminatingError和$ ExecutionContext.Host.Runspace.GetCurrentlyRunningPipeline()。stops.set_IsStopping($ true)我终于发现只使用select-object是唯一没有中止整个脚本的东西(而不仅仅是管道)。 [请注意,上面提到的一些项目需要访问我通过反射访问的私人成员。]

# This looks like it should put a zero in the pipeline but on PS 3.0 it doesn't
function stop-pipeline {
  $sp = {select-object -f 1}.GetSteppablePipeline($MyInvocation.CommandOrigin)
  $sp.Begin($true)
  $x = $sp.Process(0) # this call doesn't return
  $sp.End()
}

新方法基于OP的评论。不幸的是,这种方法更加复杂并且使用私有成员。此外,我不知道这有多强大 - 我只是让OP的例子工作并停在那里。所以FWIW:

# wh is alias for write-host
# sel is alias for select-object

# The following two use reflection to access private members:
#   invoke-method invokes private methods
#   select-properties is similar to select-object, but it gets private properties

# Get the system.management.automation assembly
$smaa=[appdomain]::currentdomain.getassemblies()|
         ? location -like "*system.management.automation*"

# Get the StopUpstreamCommandsException class
$upcet=$smaa.gettypes()| ? name -like "*upstream*"

filter x {
  [CmdletBinding()]
  param(
    [parameter(ValueFromPipeline=$true)]
    [object] $inputObject
  )
  process {
    if ($inputObject -ge 5) {
      # Create a StopUpstreamCommandsException
      $upce = [activator]::CreateInstance($upcet,@($pscmdlet))

      $PipelineProcessor=$pscmdlet.CommandRuntime|select-properties PipelineProcessor
      $commands = $PipelineProcessor|select-properties commands
      $commandProcessor= $commands[0]

      $null = $upce.RequestingCommandProcessor|select-properties *

      $upce.RequestingCommandProcessor.commandinfo =  
          $commandProcessor|select-properties commandinfo

      $upce.RequestingCommandProcessor.Commandruntime =  
          $commandProcessor|select-properties commandruntime

      $null = $PipelineProcessor|
          invoke-method recordfailure @($upce, $commandProcessor.command)

      1..($commands.count-1) | % {
        $commands[$_] | invoke-method DoComplete
      }

      wh throwing
      throw $upce
    }
    wh "< $inputObject >"

    $inputObject
  } # end process
  end {
    wh in x end
  }
} # end filter x

filter y {
  [CmdletBinding()]
  param(
    [parameter(ValueFromPipeline=$true)]
    [object] $inputObject
  )
  process {
    $inputObject
  }
  end {
    wh in y end
  }
}

1..5| x | y | measure -Sum

通过反射检索PipelineProcessor值的PowerShell代码:

$t_cmdRun = $pscmdlet.CommandRuntime.gettype()
# Get pipelineprocessor value ($pipor)
$bindFlags = [Reflection.BindingFlags]"NonPublic,Instance"
$piporProp = $t_cmdRun.getproperty("PipelineProcessor", $bindFlags )
$pipor=$piporProp.GetValue($PSCmdlet.CommandRuntime,$null)

通过反射调用方法的Powershell代码:

$proc = (gps)[12] # semi-random process
$methinfo = $proc.gettype().getmethod("GetComIUnknown", $bindFlags)
# Return ComIUnknown as an IntPtr
$comIUnknown = $methinfo.Invoke($proc, @($true))

答案 2 :(得分:1)

我知道抛出PipelineStoppedException会停止管道。以下示例将模拟您在v3.0中使用Select -first 1在v2.0中看到的内容:

filter Select-Improved($first) {
    begin{
        $count = 0
    }
    process{
        $_
        $count++
        if($count -ge $first){throw (new-object System.Management.Automation.PipelineStoppedException)}
    }
}

trap{continue}
1..3| foreach { Write-Host "Value : $_"; $_ }| Select-Improved -first 1
write-host "after"