I want to check if a string contains a numeric value. I have this code :
$string = "some string that contains 123456 in the middle"
$substring = $string.substring(27,9).Trim()
I have $substring which will be containing "123456" and I found this IsNumeric function here : In PowerShell, how can I test if a variable holds a numeric value?
The thing is that this when I'm extracting it from $string it acts like string type and IsNumeric returns false since it's comparing it to the all numeric types. and even tough it will contain a number the output of IsNumeric will be false.
Is there a better way to check if string contains numeric values?
If you want to know in PowerShell if a string contains a particular string or word then you will need to use the -like operator or the . contains() function. The contains operator can only be used on objects or arrays just like its syntactic counterpart -in and -notin .
The backslash is used to define a special character in a Regular Expression, as e.g. \t define a tab. But this is not the case for PowerShell. To define a special character in PowerShell you need to use the backtick character (See: About Special Characters), e.g. a Tab is written as `t .
The Substring method can be used on any string object in PowerShell. This can be a literal string or any variable of the type string. To use the method we will need to specify the starting point of the string that we want to extract. Optionally we can specify the length (number of characters), that we want to extract.
0. PS C:> [uint16]::MaxValue. 65535 Int is the default numeric data type in Windows PowerShell. It is a 32-bit signed integer.
The correct way to check if a given string can be turned into a number:
[string]$InString = "123456"
[Int32]$OutNumber = $null
if ([Int32]::TryParse($InString,[ref]$OutNumber)){
Write-Host "Valid Number"
$OutNumber
} else {
Write-Host "Invalid Number"
#error code here
}
then $OutNumber
will contain the number as a numeric type.
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