PoshCode Archive  Artifact [8d93ed51d1]

Artifact 8d93ed51d1fb6a8836fd2ebb2aabd594ed005a1b023cb140a2f2bbc4c6b5ca93:

  • File ISE-NativeConsole-Hooks.ps1 — part of check-in [50ddd4bb9b] at 2018-06-10 14:11:45 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: 6265
# x-archived: 2016-10-07T11:36:01
# x-published: 2016-03-21T19:54: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
}