PoshCode Archive  Artifact [d4bf671d11]

Artifact d4bf671d1144d9cbf69c8259ab94c2a20de9d1bc8c66a3305b05cb80e47bd9f6:

  • File Stop-Pipeline.ps1 — part of check-in [af1afeb202] at 2018-06-10 12:58:42 on branch trunk — Use this to stop scripts running in PowerShell.exe in mid-stride. (user: Joel Bennett size: 1153)

# encoding: ascii
# api: powershell
# title: Stop-Pipeline
# description: Use this to stop scripts running in PowerShell.exe in mid-stride.
# version: 0.1
# type: script
# author: Joel Bennett
# license: CC0
# x-poshcode-id: 1582
# x-archived: 2014-05-25T04:10:54
# x-published: 2010-01-16T11:35:00
#
#
$Wasp = Add-Type -MemberDefinition @'
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
'@ -Passthru

$null = Add-Type -Assembly System.Windows.Forms

filter Stop-Pipeline(  [scriptblock]$condition = {$true} ) {
   if (& $condition) {
      ## You need to make sure PowerShell is the foreground Window before you send Ctrl+C
      if($Wasp::SetForegroundWindow( (Get-Process -id $PID).MainWindowHandle )) {
         [System.Windows.Forms.SendKeys]::SendWait("^C")
      } else {
         Throw (New-Object System.Management.Automation.PipelineStoppedException)
      }
      $condition = { $true }  ## Make sure that once it's true, it's always true
   } else { ## Sometimes, the commands upstream manage to send out extras
      $_
   }
}