Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell. How to check that no string in array starts with some character?

I already know how to check if a string in an array DOES start with some character:

foreach ($str in $arr) {
    if ($str.StartsWith("abc")) {
        do this
    }
}

But I need the code that will have somewhat different logic: "if no string in this array starts with abc, then do this"

Please help me to build code for that with the means of Powershell. I have no clue.

like image 884
youtube2019 Avatar asked Sep 05 '25 03:09

youtube2019


1 Answers

Using member-access enumeration and this comparison operator feature:

When the input of an operator is a scalar value, the operator returns a Boolean value. When the input is a collection, the operator returns the elements of the collection that match the right-hand value of the expression. If there are no matches in the collection, comparison operators return an empty array. For example:

if (!($Arr.StartsWith("abc") -eq $True)) {
    'no string in $arr starts with abc'
}

If it concerns a very large array and you don't want to search further when any string starting with abc is already found (as the helpful suggestion from Santiago), you might also use the PowerShell Where method:

if (!($Arr.Where({ $_.StartsWith("abc") }, 'First'))) {
    'no string in $arr starts with abc'
}

Note that in comparison with PowerShell's native case sensitivity the .Net StartsWith method is case sensitive.

like image 192
iRon Avatar answered Sep 07 '25 20:09

iRon