Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains numeric value in PowerShell?

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?

like image 766
Marked One Avatar asked Jul 04 '18 10:07

Marked One


People also ask

How do you check if a string contains a Substring in PowerShell?

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 .

How do I find special characters in PowerShell?

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 .

How do I use Substring in PowerShell?

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.

What is int PowerShell?

0. PS C:> [uint16]::MaxValue. 65535 Int is the default numeric data type in Windows PowerShell. It is a 32-bit signed integer.


1 Answers

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.

like image 57
colsw Avatar answered Sep 27 '22 22:09

colsw