PowerShell: How to Check if String Starts with Specific Value


You can use the StartsWith() method in PowerShell to check if a string starts with a specific value.

One common way to use this method is to check if each string in a file starts with a specific value and, if so, add that string to an array:

$Guards = @()

Get-Content $my_file | % {Switch($_){ {$_.StartsWith("Guard")}{$Guards+=$_} }}

This particular example will check if each row in the file saved in the variable named my_file starts with the string “Guard” and, if it does, add that row to an array named Guards.

The following example shows how to use this syntax in practice.

Example: Check if String Starts With Specific Value in PowerShell

Suppose we have a file named player_info.txt saved in the following location:

  • c:\users\bobbi\player_info.txt

We can use the following syntax to view the entire contents of this file:

$my_file = "c:\users\bobbi\player_info.txt"
Get-Content $my_file

The following screenshot shows how to use this syntax in practice:

We can see that the text file contains ten lines that describe the position and ID number of various basketball players.

Suppose that we would like to create an array that only contains the rows in the file that start with “Guard”.

We can use the following syntax to do so:

$Guards = @()

Get-Content $my_file | % {Switch($_){ {$_.StartsWith("Guard")}{$Guards+=$_} }}

The following screenshot shows how to use this syntax in practice:

PowerShell check if string starts with value

Notice that only the rows in the file that start with “Guard” are added to the array named Guards:

  • Guard00453
  • Guard00299
  • Guard00225
  • Guard14992

Feel free to replace “Guard” with any value that you would like in the StartsWith() method to check if a string starts with a different value.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Check if String Exists in List of Strings
PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Replace Text in String

Leave a Reply