Casting a Type Without Exception

by Dec 30, 2008

Read-Host is a useful cmdlet to use to ask for user input. However, it returns user input always as generic string. Of course, you can always convert the user input to a more specialized type, like DateTime, to calculate time spans:

$date = [DateTime] (Read-Host 'Enter your birthday!')
New-Timespan $date (Get-Date)
$days = (New-Timespan $date (Get-Date)).TotalDays
'You are {0:0} days old!' -f $days

However, you might cause your script to crash with an exception if you enter something that cannot be converted to a date.

So, it might be safer to use the -as operator to convert a type as it does not throw an exception when conversion fails. Instead, it simply returns $null and you can then check for the conversion result and act accordingly:

$date = Read-Host 'Enter your birthday'
$date = $date -as [DateTime]
if ($date -eq $null) {
'You did not enter a date!'
} else {
New-Timespan $date (Get-Date)
$days = (New-Timespan $date (Get-Date)).TotalDays
'You are {0:0} days old!' -f $days
}