Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In PowerShell, how can I test if a variable holds a numeric value?

Tags:

powershell

In PowerShell, how can I test if a variable holds a numeric value?

Currently, I'm trying to do it like this, but it always seems to return false.

add-type -Language CSharpVersion3 @'     public class Helpers {         public static bool IsNumeric(object o) {             return o is byte  || o is short  || o is int  || o is long                 || o is sbyte || o is ushort || o is uint || o is ulong                 || o is float || o is double || o is decimal                 ;         }     } '@  filter isNumeric($InputObject) {     [Helpers]::IsNumeric($InputObject) }  PS> 1 | isNumeric False 
like image 758
Damian Powell Avatar asked Jun 07 '12 08:06

Damian Powell


People also ask

What is the $_ variable in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

How do you check if a variable is a string in PowerShell?

Both helpful and I learned that almost all variable in Powershell are considered objects. You gave me the technique to check if a variable is a string using "" -is [string] hence I mark it as answer.

How do I get the value of a variable in PowerShell?

The Get-Variable cmdlet gets the PowerShell variables in the current console. You can retrieve just the values of the variables by specifying the ValueOnly parameter, and you can filter the variables returned by name.

How can you display the type of variable that one is PowerShell?

There are different data types exist for the variable like Byte, Int32, Float, String, etc. To get the variable type, we need to use the GetType() method.


1 Answers

You can check whether the variable is a number like this: $val -is [int]

This will work for numeric values, but not if the number is wrapped in quotes:

1 -is [int] True "1" -is [int] False 
like image 114
tophatsteve Avatar answered Sep 28 '22 01:09

tophatsteve