I have array of strings

$Emails = '[email protected]','[email protected]','[email protected]' 

This array can contain from 1 to unlimited numbers of elements.

And I need to build a filter string from this array like that:

"(PrimarySmtpAddress -ne '[email protected]') -and (PrimarySmtpAddress -ne '[email protected]') -and (PrimarySmtpAddress -ne '[email protected]')" 

This is the only direct approach I could come up with:

 $out = $null foreach ($i in $ExcludedEmails) { if ($out -eq $null) { $out = "(PrimarySmtpAddress -ne '$i')" } else { $out += " -and (PrimarySmtpAddress -ne '$i')" } } 

This code produces the expected result. But I'd like to know if there's a more elegant solution using some built-in function of the String class or something like that.

Is there any?

7 Replies 7

$out = $emails | % { $matchlist -notcontains $_ } 

$out will contain all the strings in $emails that are not in $matchlist.

is there any practical difference in using $Collection -notcontains $Item instead of $Item -notin $Collection?
(and relative positive variants, of course)

Why not using -Join as
$Emails | ForEach-Object { "(PrimarySmtpAddress -ne '$_')" } -join ' -and '

@sirtao, good question, you might formally post that one. I did some quick testing from a scalar, type casting, performance view and from a first sight, it looks like there isn't a practical difference but maybe someone might come up with one considering PowerShell has some specific quirks...

@Posix, one thing you probably would like to avoid in any case, is the increase assignment operator (+=) for building strings as it is ineffective.

Slightly obscure, but concise and efficient (compared to pipeline use), using the rewex-based -replace operator:

$Emails -replace '.+', '(PrimarySmtpAddress -ne ''$&'')' -join ' -and '

Alternatively, using the intrinsic .ForEach() method:

$Emails.ForEach({ "(PrimarySmtpAddress -ne '$_')" }) -join ' -and '

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.