Pages

Monday, May 11, 2015

Powershell IsNumeric

For the longest time, I've been using a visual basic trick to determine if a variable is a numeric value.

[reflection.assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
function isNumeric([string] $a) {
    $b = ([Microsoft.VisualBasic.Information]::isnumeric($a))
    return $b
}

IsNumeric "12"
$True

IsNumeric "Bob"
$False



Looking at the code, all I am doing is type-casting the variable as a integer and seeing if I get an error. So I could simply.

Try {
      [Int]$Variable -is [Int]
} Catch {
     $false
}

So, now in my code instead of evaluating the variable if it's a numeric value, then run through a "if numeric then ____ else _____". Now I simply encapsulate my THEN _ ELSE _  portions into my Try _ Catch _.

try {
 $DaysInt = [int]$daysBack
 $EndDate = Get-Date
 $StartDate = $EndDate.AddDays(-1 * $DaysBack).ToShortDateString()
} catch {
 $StartDate = Get-Date $daysback -Format g -ErrorAction silentlycontinue
  if ($StartDate -ne $null) {
  Write-Host "you entered a date" $StartDate 
  $EndDatestr = (Read-Host "Specify an End Date (enter for today)").trim()
  if ($enddatestr -eq "") {
   $EndDate = Get-Date
  } else {
   $endDate = Get-Date $EndDateStr  
  }
 }
} 

No comments:

Post a Comment