Functions/Get-TCPWriter.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Function Get-TCPWriter
{
    <#
        .SYNOPSIS
        Returns a TCPWriter object for a given TcpClient.
 
        .DESCRIPTION
        Creates a TcpWriter, given the TcpClient (and TcpStream), and returns it.
 
        .EXAMPLE
        Get-TCPWriter -TcpClient $Client
        Returns a TCPWriter connected to the stream associated with the TCPClient.
 
        .OUTPUTS
        System.IO.StreamWriter
    #>


    [CmdletBinding()]
    [OutputType([System.IO.StreamWriter])]
    param
    (
        # TCP Client that is connected to an endpoint
        [Parameter(Mandatory   = $true,
                   HelpMessage = 'TCP Client that is connected to an endpoint')]
        [ValidateNotNullOrEmpty()]
        [Net.Sockets.TcpClient]
        $TcpClient
    )

    Try 
    {
        $TcpStream = $TcpClient.GetStream()
        $TcpWriter = New-Object -TypeName System.IO.StreamWriter -ArgumentList $TcpStream

        # We want to set autoflush to true so that we send whatever is in the stream/writer when a newline is entered
        $TcpWriter.AutoFlush = $true
    }
    Catch 
    {
        Throw $_
    }

    $TcpWriter
}