PoshCode Archive  Artifact Content

Artifact c690b0a1626b2e35c1dfa1e0ffcdd8bfd893c14b494600257752708d75f85713:

  • File Start-NamedPipe.ps1 — part of check-in [5a60c45c59] at 2018-06-10 14:13:51 on branch trunk — Start-NamedPipe (user: theDude size: 1802)

# 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
}