1

I have an array in Powershell with some strings, for example

$StringArray = {"all_srv_inf", "all_srv_inf_vir", "all_srv_inf_vir_vmw", "all_srv_rol", "all_srv_rol_iis", "all_srv_rol_dc"}

I would like to filter all strings in the array, so only the most unique ones are left over.

So, in the above example, I would have to filter "all_srv_inf", "all_srv_inf_vir" and "all_srv_rol" resulting in a string array with only these value: "all_srv_inf_vir_vmw", "all_srv_rol_iis" and "all_srv_rol_dc"

The list is actually a lot longer, so I what would be the most efficient way to filter my Powershell string array?

Thanks.

1
  • If the answer below helped you, please also consider upvoting it. Commented Sep 11, 2017 at 10:48

1 Answer 1

1

Your variable does not contain an actualy array, but rather a scriptblock that generates an array when invoked.

There are many ways to filter strings, which you can find by searching here on SO or Google. You could could try a few solutions using Measure-Command { #your code } to see how long it takes and compare the results.

My first two ideas would have been using -notmatch or -notcontains/-notin. -notmatch uses regex which are usually faster, so I would start with that. Another solution might peform better for you depending on you input data etc. so you should try different approaches and measure them.

Sample with -notmatch:

$StringArray = "all_srv_inf", "all_srv_inf_vir", "all_srv_inf_vir_vmw", "all_srv_rol", "all_srv_rol_iis", "all_srv_rol_dc"

#Build regex for items to exclude
$exclude = ('all_srv_inf', 'all_srv_inf_vir','all_srv_rol' | ForEach-Object { "^$([regex]::Escape($_))$" }) -join '|'

#Filter stringarray
$StringArray -notmatch $exclude
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Frode. I promise you I did pu a lot of time in it. Created some functions to handle it, whuch went through the array and checked if the string was a substring of one of the string in the array. Anyway, your solution to put the 'top level' strings that had to be excluded in a seperate array works very fast. Thanks again.

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.