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?