Quantcast
Channel: PowerShell.org » All Posts
Viewing all articles
Browse latest Browse all 13067

Handling errors when using methods

$
0
0

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


Viewing all articles
Browse latest Browse all 13067

Trending Articles