我在PowerShell中创建TCP客户端时尝试保留.NET类型。我有以下代码:
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
}
我非常确定$ TcpClient.Client的类型应该是System.Net.Sockets.Socket,但如果我尝试使用此函数并将返回值设置为变量,我会得到类型System 。宾语[]。如果我尝试像下面这样抛出对象:
[System.Net.Sockets.Socket]$client = New-TcpClient -RemoteHost "myhost" -Port "23"
然后,我得到了Powershell无法将System.Object []类型转换为System.Net.Sockets.Socket的异常。我该如何保留实际类型?
答案 0 :(得分:0)
您的问题是Write-Output
行。默认函数返回所有输出。那也意味着你发短信。这可以通过运行此命令来验证
(new-tcpclient -RemoteHost thing.server.com -Port 1234)[0]
Creating a TCP connection to 'thing.server.com' ...
这就是它返回System.Object[]
并且演员表失败的原因。将这些行更改为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."
...
PowerShell将像往常一样处理剩下的事情。
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
最后加上一些补充阅读:Function return value in PowerShell