Multiple where clause inside variable

Can anyone help me with the syntax here, if it’s possible?
Basically, I’m trying to create a variable with some filters to add to a where clause.

I would like to have a configuration variable that is used later in the code.

For example:


Get-UserProfiles | where-object {$_.username -notin $ProfileFilter}

Not sure if I need to modify the syntax on the variable or use a different operator, etc.


Hmmm… The -like operator is designed to work with only one wildcard filter at a time; it won’t handle multiple.

For cases like this, I’d recommend the -match operator (or -notmatch in this case). It uses regex, but once you get past that little hurdle it’s very neat for relatively straightforward asks like this. | in regex is “or”, so we’ll make use of that, and note also that regex is a partial match by default, so we need less wildcards if that’s what you want here (string ending in either of those terms).

$ProfileFilter = "(_test|local)$"

Get-UserProfiles | where-object {$_.username -notmatch $ProfileFilter}

That match string essentially says “we want either of these two things in the parentheses, and immediately after that we should have the end of the string”. $ is the “end of string” anchor in regex.

The purpose of the variable is to make it easy for someone else to configure how the script will work. They need to be able to enter plain text, not a regex.

Thanks for the idea though.

I could put the entire where clause in a variable, including the -or operators. I really want to make it simpler than that for the person running the script though.

Not exactly sure what you’re after or what the issue is.
But to me it sounds like you should parameterize the script.
So that the script/function doesn’t need to be modified in code for the scenarios you want to cover.

You can also combine the solution of Fredrik and Joel


$FilterRegex = $Filter -join '|'

Get-UserProfiles | where-object {$_.username -notmatch $FilterRegex}

Script usage

MyScript.ps1 -Filter '_test','local'

This is a huge script with a GUI. It is being run like it is an application. It already has a separate configuration file with about 30 variables that are user configurable.

can you show us how you want the script to be called with an example ?

I right-click the script and run with Powershell. Then it opens the gui.

You could explain more, What the UI will ask for ? Are you giving any inputs via textbox ? if so what all you will be giving as input. If possible please share the screenshot with your expected inputs.

I clicking a button that calls a function. The function lists all the user profiles on the computer. Then it populates a gridview with the list. I want to filter out profiles that match a certain criteria. I do not want profiles to be listed if they end with a certain substring.