首页 > 解决方案 > 如何将新的 NoteProperty 添加到 Format-Table 视图?

问题描述

我正在玩Get-NetTCPConnection作为替代品netstat,我正在尝试为-b旗帜提出解决方案。

-b 显示创建每个连接或侦听端口所涉及的可执行文件。

到目前为止,我Add-Member喜欢这样

Get-NetTCPConnection | %{ Add-Member -InputObject $_ -NotePropertyMembers @{OwningProcessName=(Get-Process -PID $_.OwningProcess).Name} -PassThru }

这似乎将 NoteProperty 添加到对象。

PS> Get-NetTCPConnection | %{ Add-Member -InputObject $_ -NotePropertyMembers @{OwningProcessName=(Get-Process -PID $_.OwningProcess).Name} -PassThru } | Get-Member -Name OwningProcessName


   TypeName: Microsoft.Management.Infrastructure.CimInstance#ROOT/StandardCimv2/MSFT_NetTCPConnection

Name              MemberType   Definition
----              ----------   ----------
OwningProcessName NoteProperty string OwningProcessName=msedge

但是,我似乎无法让该列Format-Table与所有默认属性一起显示。理想情况下,我想在不重复整个默认属性列表的情况下附加它。

我在最大化的窗口中运行了这个命令:

PS> Get-NetTCPConnection | %{ Add-Member -InputObject $_ -NotePropertyMembers @{OwningProcessName=(Get-Process -PID $_.OwningProcess).Name} -PassThru } | Format-Table -AutoSize

LocalAddress    LocalPort RemoteAddress   RemotePort State       AppliedSetting OwningProcess
------------    --------- -------------   ---------- -----       -------------- -------------
::1             50737     ::              0          Listen                     12676
::              49674     ::              0          Listen                     1180
::              49671     ::              0          Listen                     1212

标签: powershell

解决方案


文档中它说“对象类型决定了每列中显示的默认布局和属性,但您可以使用 Property 参数来选择要查看的属性。”

这意味着您需要使用-Property参数并列出您希望查看的属性

Get-NetTCPConnection | Foreach-Object { 
    $_ | Add-Member -NotePropertyMembers @{OwningProcessName=($_.OwningProcess).Name} -PassThru |
} | 
Format-Table -Property LocalAddress, LocalPort, RemoteAddress, RemotePort, State, AppliedSetting, OwningProcess, OwningProcessName -AutoSize

或者输出仅包含您需要的属性并添加了新属性的新对象:

Get-NetTCPConnection | Foreach-Object { 
    $_ | Add-Member -NotePropertyMembers @{OwningProcessName=($_.OwningProcess).Name} -PassThru |
    Select-Object LocalAddress, LocalPort, RemoteAddress, RemotePort, State, AppliedSetting, OwningProcess, OwningProcessName
} | 
Format-Table -AutoSize

更改Format-Tablecmdlet 显示的默认属性或许可以通过编辑C:\windows\systems32\windowspowershell\v1.0\Types.ps1xml. 我在这里这里找到了有关此的博客,以防您感兴趣。


推荐阅读