24

I have some code that takes in a string,

Foreach($user in $allUsers){
    if($user.DisplayName.ToLower().Contains("example.com") -or $user.DisplayName.ToLower()) {
    } else {
        $output3 = $externalUsers.Rows.Add($user.DisplayName)
    }
}

Part of the if right after the -or I need to check if the string does not contain an @ sign. How can I check to see if the @ sign is missing?

2
  • 3
    .Contains() returns a boolean. Just check for !($user.DisplayName.ToLower().Contains("@"))? Commented Jan 15, 2015 at 18:30
  • Perfect! If you create this as an answer I will accept it. Commented Jan 15, 2015 at 18:32

1 Answer 1

50

There are a million ways to do it, I would probably go for the following due to readability:

$user.DisplayName -inotmatch "@"

The -match operator does a regex match on the the left-hand operand using the pattern on the right-hand side.

Prefixing it with i make it explicitly case-insensitive, and the not prefix negates the expression

You could also do:

-not($user.DisplayName.ToLower().Contains("@"))
or
!$user.DisplayName.ToLower().Contains("@")

For simple wildcard text-matching (maybe you hate regex, what do I know?):

$user.DisplayName -notlike "*@*"

Or alternatively look for the substring with IndexOf;

$user.DisplayName.IndexOf("@") -eq (-1)
Sign up to request clarification or add additional context in comments.

1 Comment

I like the clearest way with -inotmatch.

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.