PowerShell: How to Check if Input Value Exists in Array


Often you may want to check if an input value provided by a user in PowerShell exists in a particular array.

You can use the following syntax to do so:

$user_input -in $my_array

This particular example checks if the user input value stored in the variable named $user_input exists in the array named $my_array.

This statement will either return True or False.

You can also use the -notin operator to check if the user input value does not exist in an array:

$user_input -notin $my_array

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

Example: How to Check if Input Value Exists in Array in PowerShell

Suppose we create an array named $good_teams that contains the names of various basketball teams and then we use the Read-Host cmdlet to prompt the user to enter a team name.

We can use the -in operator to check if the value provided by the user exists in the array:

$good_teams = @('Mavs', 'Lakers', 'Spurs', 'Nets')
$user_input = Read-Host 'Enter team name'
$user_input -in $good_teams

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

PowerShell check if input value exists in array

In this particular example we typed in Lakers for the user input.

Since this team name exists in the array named $good_teams, the -in operator returns True.

Suppose instead that we typed in Celtics for the user input:

Since this team name does not exist in the array named $good_teams, the -in operator returns False.

Note: You can find the complete documentation for the -in, -notin and other comparison operators in PowerShell here.

Related Tutorials

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

PowerShell: How to Replace Multiple Strings in File
PowerShell: How to Replace Special Characters in String
PowerShell: How to Replace Text in String

Leave a Reply