How can I sort a list but add a specific item to the top? For example:
apple
orange
peach
pear
grapefruit
Let’s say I want to sort the list alphabetically but I want peach up top and I only want it to appear once. I would also like Grapefruit to be 2nd. Thanks in advance!
Thank you Don! Lesson learned don’t paste in the forums unless I’m on the text tab.
I tried to go back and edit it but the forums stared giving me a 401 error around that time. I hope I did not cause that.
Anyway as far as a real world example I am trying to write a script that sets the binding order for all of the network interfaces on Hyper-V hypervisors. I have everything working now I just need to be able to sort the NICs. So the real lines look something like this. . .
There’d be no easy way to do this. You’d probably pipe your list to Sort-Object first, and grab that in a variable. Then you’d have to construct a new array, adding objects to it in whatever order you want, and then output that array. There’s not really a more elegant approach.
I’d be happy to have ya putting stuff in variables instead of in files as an interim holding area ;).
So, a couple of things: Arrays don’t “have” commas or carriage returns. An array is (basically) a collection of objects. PowerShell interprets comma-separated lists as arrays ($array = 1,2,3) and when it reads a file, it uses newline (CRLF) characters to return each line of the file as an object - meaning the entire file is interpreted as an array of strings.
So if I had things at the top in $topmost ($topmost = ‘peach’,‘plum’), and I had other objects in $main ($main = ‘apple’,‘pear’,‘mango’), I would probably do:
In my real word array of strings the duplicates are going to be there so I joined (+) topmost and sorted main so I could filter out the duplicates. The variable we are calling “main” is a list of objects from a registry key I can not predict or control and the 2 objects I want sorted to the top are already in there. So I like this and I think you have helped me greatly and now I don’t have to rely on saving to a file and getting content out of a file to sort my list and what I posted above works exactly like I need. Thanks again this is awesome!