Powershell – Check If String Starts With IgnoreCase

Checking a string is startswith some character(or a string) is common need for every kind of powershell script. We can use the powershell’s like operator with wildcard character to check the startswith string for both case-sensitive and case-insensitive.

The following method is used to check if a string is starts with another string using like operator. By default like operator ignore the case-sensitive check.

$strVal ='Hello world'
if($strVal -like 'hello*') {
      Write-Host 'Your string is start with hello'
} else {
      Write-Host 'Your string does not start with hello"'
}

To perform a Case-Sensitive comparison just prefix the word “c” with like operator (“clike”).

$strVal ='Hello world'
if($strVal -clike 'Hello*') {
      Write-Host 'True'
} else {
      Write-Host 'False'
}

We can also use the .NET’s string extension function StartsWith to check whether a string is startswith a set of characters.

The following method is used to check if a string is start with other string.

$strVal ='Hello world'
if($strVal.StartsWith('Hello')) {
     Write-Host 'True'
} else {
     Write-Host 'False'
}

Use the following method if you want to ignore the case in start with check.

$strVal ='Hello world'
if($strVal.StartsWith('hello','CurrentCultureIgnoreCase')) {
     Write-Host 'True'
} else {
     Write-Host 'False'
}

Advertisement

Leave a Comment