TCP Sender
suggest changeFunction Send-TCPMessage {
Param (
[Parameter(Mandatory=$true, Position=0)]
[ValidateNotNullOrEmpty()]
[string]
$EndPoint
,
[Parameter(Mandatory=$true, Position=1)]
[int]
$Port
,
[Parameter(Mandatory=$true, Position=2)]
[string]
$Message
)
Process {
# Setup connection.
# GetHostAddresses returns IPAddress objects. Parse expects a string.
$Address = [System.Net.Dns]::GetHostAddresses($EndPoint) | Select-Object -First 1
$Socket = New-Object System.Net.Sockets.TcpClient($Address, $Port)
# Setup stream writer
$Stream = $Socket.GetStream()
$Writer = New-Object System.IO.StreamWriter($Stream)
# A string piped to ForEach-Object is enumerated as characters.
$Writer.WriteLine($Message)
$Writer.Flush()
# Close connection and stream
$Stream.Close()
$Socket.Close()
}
}
Send a message with:
Send-TCPMessage -Port 29800 -Endpoint 192.168.0.1 -Message "My first TCP message!"
Note: A firewall can block this. The port above must be open, and the listener must use that same port.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents