3

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"
}

2 Answers 2

2

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.

0
0

In addition to JosefZ's answer the automatic variable $Error contains an array of errors, so you could look at $Error.Count property to see if it went up. I think -ErrorVariable though is the best answer. see Get-Help about_AutomaticVariables for details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.