Handling errors when using methods

Hi Don,

I’m always struggling with methods resulting in the error: You cannot call a method on a null-valued expression.
For example:
$Users = Get-ADuser -Filter {DisplayName -like ‘Jon*’} -Properties *
$UserObj = @()
Foreach ($User in $Users) {
$UserProp = @{Name=$User.DisplayName;
LastLoggedOn=$User.LastLogonDate.ToShortDateString()}
$Obj = New-Object -Type PSObject -Property $UserProp
$UserObj += $Obj
}
$UserObj

When the lastlogondate of the user is empty the method ToShortDateString() is giving the error.

Another example is with Get-MailboxStatistics for Exchange and the TotalItemSize you can convert to MB of GB by using TotalItemSize.Value.ToMB()
If the mailbox was never used the error is thrown.

What is the best approach to intercept this?

Thanks,
Peter

Hi. Keep in mind I’m not the only on here, though ;). If you ask for me specifically you may keep some other helpful folks from offering an answer!

You’ll want to use a Try…Catch block (help about_try*). For cmdlets that throw a non-terminating error, you have to use -ErrorAction to convert to a terminating exception, since you can only trap those. For a method, set $ErrorActionPreference=‘Stop’ before trying the method, and $ErrorActionPreference=‘Continue’ after the method, to put it back to normal.

Error handling is a pretty beefy topic, but hopefully that gets you started.

Thanks!

Result should look like this:

$Users = Get-ADuser -Filter {DisplayName -like ‘Jon*’} -Properties *
$UserObj = @()
Foreach ($User in $Users) {
$ErrorActionPreference = “Stop”
Try {$LastLoggedOn = $User.LastLogonDate.ToShortDateString()} Catch {$LastLoggedOn = “N/A”} Finally {$ErrorActionPreference = “Continue”}
$UserProp = @{Name=$User.DisplayName;
LastLoggedOn=$LastLoggedOn}
$Obj = New-Object -Type PSObject -Property $UserProp
$UserObj += $Obj
}
$UserObj