PoshCode Archive  Artifact [7a9c7661fe]

Artifact 7a9c7661fee593d9ea2cc6259ae65dc7a46997d07df7407612ca21775f3b26ef:

  • File ISE-NativeConsole-Hooks.ps1 — part of check-in [8447c10e3c] at 2018-06-10 13:33:15 on branch trunk — A demo for some fun native-console hooking in PowerShell ISE (user: Joel Bennett size: 1560)

# encoding: ascii
# api: powershell
# title: ISE NativeConsole Hooks
# description: A demo for some fun native-console hooking in PowerShell ISE
# version: 0.1
# type: function
# author: Joel Bennett
# license: CC0
# function: receive-output
# x-poshcode-id: 3935
# x-archived: 2013-02-13T05:50:05
# x-published: 2013-02-09T05:49:00
#
#
# Uses NativeConsole, which is available under a bunch of Open Source licenses
# http://poshconsole.codeplex.com/SourceControl/changeset/view/f9bb2b127402#Huddled/Interop/NativeConsole.cs
add-type -Path ~\Projects\PoshConsole\Huddled\Interop\NativeConsole.cs

$NativeConsole = New-Object Huddled.Interop.NativeConsole

$ConsoleError = Register-ObjectEvent -InputObject $NativeConsole -EventName WriteError -Action { 
    Add-Content -Path $Pwd\Error.log -Value $EventArgs.Text
    Add-Content -Path $Pwd\Output.log -Value $EventArgs.Text
    Write-Error $EventArgs.Text
    # Fake output, so I get to see it immediately
    Write-Host $EventArgs.Text -ForegroundColor Red
}

$ConsoleOutput = Register-ObjectEvent -InputObject $NativeConsole -EventName WriteOutput -Action {
    Add-Content -Path $Pwd\Output.log -Value $EventArgs.Text
    Write-Output $EventArgs.Text 
    # Fake output, so I get to see it immediately
    Write-Host $EventArgs.Text
}

# Now just call any console app, because NativeConsole's going to handle the output
cmd /c "dir && dir brokenthing"

# To get the real output, receive-it
function receive-output {
    Receive-Job $ConsoleOutput, $ConsoleError
}