首页 > 解决方案 > 将 Get-NetTCPConnection 的输出写入数组 - 无输出

问题描述

我正在尝试将 PowerShell cmdlet 的值写入Get-NetTCPConnection数组,但没有将任何内容写入列表。

$list= @()

$outputs = Get-NetTCPConnection 

foreach ($output in $outputs) {
    $obj = New-Object PSObject -Property @{
        TheLocalAddress  = "EMPTY"
        TheLocalPort     = "EMPTY"
        TheRemoteAddress = "EMPTY"
        TheRemotePort    = "EMPTY"
    }

    $obj.TheLocalAddress  = $output.LocalAddress
    $obj.TheLocalPort     = $output.LocalPort
    $obj.TheRemoteAddress = $output.RemoteAddress
    $obj.TheRemotePort    = $output.RemotePort

    $list += $obj
}
$list

标签: powershell

解决方案


如果属性不需要前缀The,为什么不使用

$list = Get-NetTCPConnection | Select-Object LocalAddress,LocalPort,RemoteAddress,RemotePort

还是更高效[PSCustomObject]

$list = foreach ($Conn in Get-NetTCPConnection) {
    [PSCustomObject]@{
        TheLocalAddress  = $Conn.LocalAddress
        TheLocalPort     = $Conn.LocalPort
        TheRemoteAddress = $Conn.RemoteAddress
        TheRemotePort    = $Conn.RemotePort
    }
}
$list

推荐阅读