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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With