0

I have multiple services. Suppose i starts with A . When I execute

Get-Service A* - It will display services as output starting with A.

I am sorting complete output except one and want that to be on top of my list once sorted. I am using below command.

Get-Service -DisplayName A* |Sort-Object {$_.Name -ne 'AK'}

It is listing all output in sorted way and AK is on top Like below .

AK
AN
AR
AS

and so on . This is only keeping AK on top and sorting others. I want to do same thing for 2 services. AK and then AR(suppose)- This both should be always in AK and AR order at top then other services need to sort. How to add this in existing code for AR.

2 Answers 2

1

Try the -notin Operator, you can specify an array of excludes:

Get-Service A* | Sort-Object {$_.name -notin "AK","AR"}

This way the AK and AR service will be on top of the sorted list

EDIT: for V2 simple and easy:

Get-Service A* | Sort-Object {"AK","AR" -notcontains $_.name}
Sign up to request clarification or add additional context in comments.

3 Comments

When running it is saying "You must provide a value expression on the right-side of the '-' operator"
What powershell version are you on?
I have v2 in some machine and v4 in some machine. -ne was working on both for 1 to exclude .
1

You need -notin and ():

'AK','AN','AR','AS' | sort {$_ -notin ('AN', 'AS')}

Or with PS 2.0:

'AK','AN','AR','AS' | sort {[Array]::IndexOf(('AN', 'AS'), $_) -eq -1}

Or (thanks to @Mathias):

'AK','AN','AR','AS' | sort {('AN', 'AS') -notcontains $_}

2 Comments

I added V2 script.
You could use -notcontains as well: sort { ('AN', 'AS') -notcontains $_ }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.