PoshCode Archive  Artifact [b420ed976a]

Artifact b420ed976ac34534c312cd8d69ca3a748ed071ff8d09c4923075a02e7f1ad381:

  • File ISE-NativeConsole-Hooks.ps1 — part of check-in [ed2baa9b86] at 2018-06-10 14:11:47 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: 6266
# x-archived: 2016-10-07T11:36:06
# 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
}