Search code examples
powershellduplicateshashtable

Remove duplicates after ConvertFrom-StringData in a oneliner


I have, for example, this one liner:

get-process | select id, processname | %{$_.processname +"="+ $_.id} | ConvertFrom-StringData

which returns a key and value pair of each process and its id. My goal is to remove any processes with duplicated name and leaving only one of them (for example, I want to be left with only one entry of svchost), in a one liner. Nothing seems to be working for me, and im not sure that ConvertFrom-StringData is the right direction, and do not understand how it succeeds converting it to hashtable with duplicated keys.


Solution

  • If you are looking to get each process once but still keep reference to the IDs you can use Group-Object on ProcessName then create custom objects from that that contain what you want.

    Get-Process | Group-Object ProcessName | ForEach-Object {
        [pscustomobject]@{
            ProcessName = $_.Name
            IDs         = $_.Group.Id
        } }
    

    Output

    ProcessName                                                                  IDs
    -----------                                                                  ---
    acumbrellaagent                                                             7288
    aesm_service                                                               17512
    ApplicationFrameHost                                                       16704
    armsvc                                                                      5240
    assystResetService                                                          5232
    atmgr                                                                      18984
    audiodg                                                                    15216
    Calculator                                                                  6128
    CamMute                                                                     5616
    CcmExec                                                                     5252
    chrome                                               {3348, 3848, 4196, 4416...}