Testing Numbers and Date

by Jan 11, 2013

With a bit of creativity (and the help from the -as operator), you can create powerful test functions. These two test for valid numbers and valid DateTime information:

PS> function Test-Numeric($Value) { ($Value -as [Int64]) -ne $null }
PS> function Test-Date($Value) { ($Value -as [DateTime]) -ne $null }

If things get more complex, you can combine tests. This one tests for valid IP addresses:

function Test-IPAddress($Value) {
(
$Value -as [System.Net.IPAddress]) -ne $null -and ($Value -as [Int]) -eq $null
}

Twitter This Tip! ReTweet this Tip!