# encoding: ascii
# api: powershell
# title: Start-NamedPipe
# description: Start-NamedPipe
# version: 0.1
# type: function
# author: theDude
# license: CC0
# function: Start-NamedPipe
# x-poshcode-id: 6354
# x-archived: 2016-05-28T20:40:14
# x-published: 2016-05-23T23:52:00
#
#

function Start-NamedPipe {
    [OutputType([System.Management.Automation.Job])]
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string] $Name
    )

    $job = Start-Job -Name "Named Pipe: $Name" -ScriptBlock {

        $pipe = New-Object System.IO.Pipes.NamedPipeServerStream($using:Name)
        try {
            $pipe.WaitForConnection()

            $sr = New-Object System.IO.StreamReader($pipe)
            try {
                while ($null -ne ($data = $sr.ReadLine())) {
                    $data
                }
            }
            finally { 
                $sr.Dispose()
            }
        }
        finally {
            $pipe.Dispose()
        }

    }

    $job
}

function Write-NamedPipe {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string] $Name
    )

    $pipe = New-Object System.IO.Pipes.NamedPipeClientStream($Name);
    try {
        $pipe.Connect();

        $sw = New-Object System.IO.StreamWriter($pipe);
        try {
            $sw.WriteLine("Go"); 
            $sw.WriteLine("start abc 123"); 
            $sw.WriteLine('exit'); 
        }
        finally {
            $sw.Dispose();
        }
    }
    finally {
        $pipe.Dispose();
    }
}

function Read-NamedPipe {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string] $Name
    )

    $job = Get-Job -Name "Named Pipe: $Name"
    $job | Receive-Job
}
