General Question / Commandlet / Object Output - get-nettcpconnection / get-process RRS feed

  • Question

  • Looking to piece together two things:

    The get-process command - which will list running processes on a device, and the get-nettcpconnection - which will show ports that, based on the filter/command, are listening.

    What I'm finding is that when I manually enter the commands I want to a command line - the output is readable and useful.

    When I pipe the commands to a variable (to step through each line when required), the output is less than visually appealing - while I know what I'm looking at, the folks I would turn this over to may initially *not*.

    What is it about the way I'm doing this that is creating aesthetically unfriendly output? 

    Thanks in advance, I appreciate all suggestions, pointers and information

    $listenerlist = (get-nettcpconnection | ? State -Like Listen | Sort-Object OwningProcess)
    foreach ($listeneritem in $listenerlist)
        write-host ""
        Write-Host $listeneritem
        (Get-Process -Id $listeneritem.OwningProcess | Sort-Object Name)

    Sample Output:

    MSFT_NetTCPConnection (InstanceID = "")
        393      31     6412      11460             15248   0 RouterNT     

    Thursday, January 2, 2020 8:10 PM

All replies

  • Run the following and you will see what is happening.

    The items have no usable output because you are trying to output a compex object with a command that does nothing useful as text.

    $listenerlist = get-nettcpconnection | ? State -Like Listen | Sort-Object OwningProcess
    foreach($listeneritem in $listenerlist){
        write-host "" -fore green
        Write-Host $listeneritem.Name -fore green
        Get-Process -Id $listeneritem.OwningProcess | Sort-Object Name

    To get friendly output just do this:

    Get-NetTCPConnection -State Listen | 
            Get-Process -Id $_.OwningProcess
        } |
        Sort-Object ProcessName

    I suggest that you should take some time to learn PowerShell before trying to use it.  Copying from the Internet will only lead you in the wrong direction.  Most things you will find are either wrong or badly written.

    Learning to script properly with PowerShell


    Thursday, January 2, 2020 9:02 PM