Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell string does not contain

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?

like image 875
Grady D Avatar asked Jan 15 '15 18:01

Grady D


1 Answers

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)
like image 78
Mathias R. Jessen Avatar answered Sep 28 '22 11:09

Mathias R. Jessen