PowerShell: How to Check if a Variable is Numeric


Often you may want to check if a variable is numeric in PowerShell.

You can use the following syntax to do so:

$my_variable -match "^[\d\.]+$"

This particular example checks if the variable named $my_variable is a numeric value and returns either True or False.

This syntax uses the -match command to check if each character in the variable is either a digit ( \d ) or a decimal place ( \. ) from the beginning ( ^ ) of the string to the end ( $ ) of the string.

The following examples show how to use this syntax in practice.

Example: How to Check if a Variable is Numeric in PowerShell

Suppose we have a variable with the following value:

  • 546

We can use the following syntax to check if this variable is numeric:

$my_variable = 546
$my_variable -match "^[\d\.]+$"

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

PowerShell check if variable is numeric

This returns True since the variable named $my_variable is indeed numeric.

Suppose we have a variable with the following value:

  • 546.22

We can use the following syntax to check if this variable is numeric:

$my_variable = 546.22
$my_variable -match "^[\d\.]+$"

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

PowerShell check if variable is numeric with decimal point

This returns True since the variable named $my_variable is a number with a decimal point.

Suppose we have a variable with the following value:

  • 546.22AA

We can use the following syntax to check if this variable is numeric:

$my_variable = "546.22AA"
$my_variable -match "^[\d\.]+$"

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

PowerShell check if variable is numeric with letters and numbers

This returns False since the variable named $my_variable contains a combination of numbers and letters.

Related Tutorials

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

PowerShell: How to Replace Text in String
PowerShell: How to Extract Text Between Two Strings
PowerShell: How to Check if String Exists in List of Strings
PowerShell: How to Replace Every Occurrence of String in File

Leave a Reply