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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With