String is numeric?

This topic contains 0 replies, has 1 voice, and was last updated by Profile photo of Forums Archives Forums Archives 5 years, 5 months ago.

  • Author
    Posts
  • #6058

    by MasterOfTheHat at 2013-03-21 06:58:12

    This morning I needed to filter through the results of a script I've written to return stale users in AD, and I needed to eliminate all users whose EmployeeID field was non-numeric. My first instinct was to look for a native posh equivalent of VB's IsNumeric() function. Apparently, it doesn't exist... What I did find was that several people recommended the following function as the best way to emulate IsNumeric().

    Agree? Disagree? Other options? This function is simple and it does what I need it to, but it kind of surprises me that this is the best solution.

    function isNumeric ($x) {
    try {
    0 + $x | Out-Null
    return $true
    } catch {
    return $false
    }
    }

    by bgenwell at 2013-03-21 07:01:24

    I could see matching based on regex:

    $user | ?{$_.employeeid -notmatch "\d"}

    by mjolinor at 2013-03-21 07:35:26

    if ([string]($x -as [int]))

    should have the same effect.

    by MasterOfTheHat at 2013-03-21 09:49:06

    After a small tweak to your code and a small tweak to my function, It looks like they're doing the same thing:
    function isNumeric ($x) {
    if($x -eq $null)
    {
    return $false
    }
    try {
    0 + $x | Out-Null
    return $true
    } catch {
    return $false
    }
    }

    PS > $staleUsers | % { "{0} - {1} - {2}" -f $_.EmployeeID, [bool]($_.EmployeeID -as [int]), $(isNumeric($_.EmployeeID)) }
    7205 - 7205 - True
    - 0 - False
    - 0 - False
    6872ATC - False - False

    by Nobody at 2013-03-21 11:16:25

    I was shown this way.

    [void][reflection.assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
    $a = 1
    [Microsoft.VisualBasic.Information]::isnumeric($a)

    edit:
    http://technet.microsoft.com/en-us/libr ... 76889.aspx

    by poshoholic at 2013-03-21 12:15:58

    I've always just used a simple regex for this.
    $x -match '^\d+$'
    If that returns true, the string is a positive integer. Otherwise it returns false.

    Here's a version that supports negative and decimal values as well:
    $x -match '^-?(\.\d+|\d+(\.\d*)?)$'
    That's messy though. If you really want support for negative integers and decimal values as well, you can simply check it like this:
    $numericValue = $null
    if (-not ([double]]$numericValue))) {
    throw 'Not a double!'
    }

    And of course you can use int instead of double or uint32 if you want an unsigned integer value, etc.

    by MasterOfTheHat at 2013-03-21 13:07:36

    About as many approaches as there are scripters... Thanks for the info, guys. At least it was a legitimate question and not something obvious that I'd just missed.

You must be logged in to reply to this topic.