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().by bgenwell at 2013-03-21 07:01:24
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
}
}
I could see matching based on regex:by mjolinor at 2013-03-21 07:35:26
$user | ?{$.employeeid -notmatch "\d"}
by MasterOfTheHat at 2013-03-21 09:49:06if ([string]($x -as [int]))
should have the same effect.
After a small tweak to your code and a small tweak to my function, It looks like they’re doing the same thing:by Nobody at 2013-03-21 11:16:25function 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
I was shown this way.by poshoholic at 2013-03-21 12:15:58
[void][reflection.assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
$a = 1
[Microsoft.VisualBasic.Information]::isnumeric($a)
edit:
http://technet.microsoft.com/en-us/libr … 76889.aspx
I’ve always just used a simple regex for this.by MasterOfTheHat at 2013-03-21 13:07:36$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.
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.