How to show only the error message

Hi all,

I want to get input from the user and if the input is not existed to write the error on the console.

for example:

$UserName = Read-Host "[Please Enter User Name]"
Get-MailboxStatistics -identity $UserName | ft TotalItemSize, TotalDeletedItemSize

Now if the user will enter a wrong user name the error will be displayed on the console:

Get-MailboxStatistics : The specified mailbox “wre” doesn’t exist.
At C:\Users\Desktop\Scripts\Menus.ps1:73 char:5

  • Get-MailboxStatistics -identity $UserName | ft TotalItemSize, Tot ...
    
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : NotSpecified: (:slight_smile: [Get-MailboxStatistics], ManagementObjectNotFoundException
    • FullyQualifiedErrorId : [Server=,RequestId=19e1e50e-eff1-4339-8f8c-54a3415d4a04,TimeStamp=26/09/202
      1 10:27:29] [FailureCategory=Cmdlet-ManagementObjectNotFoundException] B67888C6,Microsoft.Exchange.Management.MapiTa
      sks.GetMailboxStatistics

Now, i want to display only the “The specified mailbox “wre” doesn’t exist.” which is in the $Error[0].Exception.Message

Thanks in advance.

Hi dady,

You could put the command into try…catch.

$UserName = Read-Host "[Please Enter User Name]"
try {
    Get-MailboxStatistics -identity $UserName -ErrorAction 'Stop' | Format-Table TotalItemSize, TotalDeletedItemSize
}
catch {
    Write-Output $_.Exception.Message
}

1 Like

Thanks, LogicalToolkit

That worked great.