kernel32/PeekNamedPipe.ps1

function PeekNamedPipe
{
    <#
    .SYNOPSIS
 
    Copies data from a named or anonymous pipe into a buffer without removing it from the pipe. It also returns information about data in the pipe.
 
    .PARAMETER PipeHandle
 
    A handle to an instance of a named pipe. This handle must be created by the CreateNamedPipe function.
 
    .NOTES
 
    Author: Jared Atkinson (@jaredcatkinson)
    License: BSD 3-Clause
    Required Dependencies: PSReflect
    Optional Dependencies: None
     
    (func kernel32 PeekNamedPipe ([Bool]) @(
        [IntPtr], #_In_ HANDLE hNamedPipe
        [byte[]], #_Out_opt_ LPVOID lpBuffer
        [UInt32], #_In_ DWORD nBufferSize
        [UInt32].MakeByRefType(), #_Out_opt_ LPDWORD lpBytesRead
        [UInt32].MakeByRefType(), #_Out_opt_ LPDWORD lpTotalBytesAvail
        [UInt32].MakeByRefType() #_Out_opt_ LPDWORD lpBytesLeftThisMessage
    ) -EntryPoint PeekNamedPipe -SetLastError)
 
    .EXAMPLES
    #>


    param
    (
        [Parameter(Mandatory = $true)]
        [IntPtr]
        $PipeHandle,

        [Parameter()]
        [UInt32]
        $SizeToRead = 0x200
    )

    $lpBuffer = New-Object -TypeName byte[]($SizeToRead)
    [UInt32]$lpBytesRead = 0
    [UInt32]$lpTotalBytesAvail = 0
    [UInt32]$lpBytesLeftThisMessage = 0

    $SUCCESS = $kernel32::PeekNamedPipe($PipeHandle, $lpBuffer, $lpBuffer.Length, [ref]$lpBytesRead, [ref]$lpTotalBytesAvail, [ref]$lpBytesLeftThisMessage)

    if(-not $SUCCESS)
    {
        throw "[PeekNamedPipe] Error: $(([ComponentModel.Win32Exception] $LastError).Message)"
    }

    $props = @{
        BytesRead = $lpBytesRead
        TotalBytesAvailable = $lpTotalBytesAvail
        BytesLeftThisMessage = $lpBytesLeftThisMessage
        Buffer = $lpBuffer
    }
    New-Object -TypeName psobject -Property $props
}