0

I'm trying to retain the .NET type when creating a TCP client in powershell. I have the following code:

function New-TcpClient() {
[CmdletBinding(PositionalBinding=$true)]
param (
    [Parameter(Mandatory=$true)]
    [String]
    $RemoteHost,

    [Parameter(Mandatory=$true)]
    [Int32]
    $Port
)

Write-Output "Creating a TCP connection to '$RemoteHost' ..."
$TcpClient = New-Object System.Net.Sockets.TcpClient($RemoteHost, $Port)
if ($TcpClient.Connected) {
    Write-Output "A connection to '$RemoteHost' on port '$Port' was successful."
} else {
    throw "A connection could not be made to '$RemoteHost' on port '$Port'."
}

return $TcpClient.Client
}

I'm pretty sure the type of $TcpClient.Client should be System.Net.Sockets.Socket, but what if I try to use this function and set the return value to a variable, I get the type System.Object[]. If I try to cast the object like the following:

[System.Net.Sockets.Socket]$client = New-TcpClient -RemoteHost "myhost" -Port "23"

Then, I get the exception that Powershell cannot convert the type System.Object[] to System.Net.Sockets.Socket. How should I go about retaining the actual type?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Ci3
  • 4,632
  • 10
  • 34
  • 44

1 Answers1

0

Your issue is the lines that have Write-Output. Be default function return all output. That would mean you text as well. This can be verified from running this command

(new-tcpclient -RemoteHost thing.server.com -Port 1234)[0]
Creating a TCP connection to 'thing.server.com' ...

That is why it is returning System.Object[] and the cast is failing. Change those lines to Write-Host

...
Write-Host "Creating a TCP connection to '$RemoteHost' ..."
$TcpClient = New-Object System.Net.Sockets.TcpClient($RemoteHost, $Port)
if ($TcpClient.Connected) {
    Write-Host  "A connection to '$RemoteHost' on port '$Port' was successful."
...

And PowerShell will handle the rest like it always does.

PS C:\Users\mcameron> (new-tcpclient -RemoteHost thing.server.com -Port 1234).GetType().FullName
Creating a TCP connection to 'thing.server.com' ...
A connection to 'thing.server.com' on port '1234' was successful.
System.Net.Sockets.Socket

Top it off with some supplementary reading: Function return value in PowerShell

Community
  • 1
  • 1
Matt
  • 45,022
  • 8
  • 78
  • 119