Tomer
Tomer

Reputation: 55

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.

Upvotes: 3

Views: 308

Answers (2)

Abraham Zinala
Abraham Zinala

Reputation: 4694

Alternatively from @Daniel's helpful answer, if you're not worried about the ID's, you can use the -Unique switch that's availble in Select-Object, and Sort-Object which I will use in this example.

Get-Process | Foreach-Object -Process {
    [PSCustomObject]@{
        Name = $_.Name 
        ID   = $_.Id
    } 
} | Sort-Object -Property Name -Unique

fancy huh? Well, yeah, but not necessary. This can still be accomplished by just selecting the properties and piping it to get sorted:

Get-Process  | Sort-Object -Property Name -Unique | Select-Object -Property Name, ID

There is also Get-Unique which will give you similar results.

Upvotes: 1

Daniel
Daniel

Reputation: 5114

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...}

Upvotes: 6

Related Questions