Howto check if a powershell command succeeded or not?

13,165

Read Set-CASMailbox reference:

  • OwaMailboxPolicy parameter:

The OwaMailboxPolicy parameter specifies the Outlook on the web mailbox policy for the mailbox. You can use any value that uniquely identifies the Outlook on the web mailbox policy. For example:

  • Name
  • Distinguished name (DN)
  • GUID

The name of the default Outlook on the web mailbox policy is Default.

Read about_CommonParameters (the parameters that can be used with any cmdlet), apply either ErrorVariable or ErrorAction:

ErrorVariable:

Set-CASMailbox -Identity:blocks.5 -OWAMailboxPolicy "DoNotExists" -ErrorVariable test
if ($test.Count -neq 0)      ### $test.GetType() is always ArrayList
{
    Write-Host "The Set-CASMailbox command failed: $test"
}
else
{
    Write-Host "The Set-CASMailbox command completed correctly"
}

ErrorAction and Try,Catch,Finally (read about_Try_Catch_Finally how to use the Try, Catch, and Finally blocks to handle terminating errors):

try {
    Set-CASMailbox -Identity:blocks.5 -OWAMailboxPolicy "DoNotExists"  -ErrorAction Stop
                ### set action preference to force terminating error:  ↑↑↑↑↑↑↑↑↑↑↑↑ ↑↑↑↑
    Write-Host "The Set-CASMailbox command completed correctly"
}  
catch {
    Write-Host "The Set-CASMailbox command failed: $($error[0])"  -ForegroundColor Red
}

In any case, read Write-Host Considered Harmful.

Share:
13,165

Related videos on Youtube

Sonnenbiene
Author by

Sonnenbiene

Updated on September 18, 2022

Comments

  • Sonnenbiene
    Sonnenbiene over 1 year

    Is it possible to check if a powershell command succeeded or not?

    Example:

    Set-CASMailbox -Identity:blocks.5 -OWAMailboxPolicy "DoNotExists"

    caused the error:

    Outlook Web App mailbox policy "DoNotExists" wasn't found. Make sure you typed the policy name correctly.
        + CategoryInfo          : NotSpecified: (0:Int32) [Set-CASMailbox], ManagementObjectNotFoundException
        + FullyQualifiedErrorId : 9C5D12D1,Microsoft.Exchange.Management.RecipientTasks.SetCASMailbox
    

    I think that it should be possible to fetch the FullyQualifiedErrorId so I tried the following:

    $test = Set-CASMailbox -Identity:blocks.5 -OWAMailboxPolicy "DoNotExists"

    But it looks like the error isn´t transferred into the test variable.

    So what is the correct way here to perform something like:

    $test = Set-CASMailbox -Identity:blocks.5 -OWAMailboxPolicy "DoNotExists"
    if ($test -eq "error")
    {
    Write-Host "The Set-CASMailbox command failed"
    }
    else
    {
    Write-Host "The Set-CASMailbox command completed correctly"
    }