Howto check if a powershell command succeeded or not?
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.
-
Cmdlet Input and Output Types. If the Output Type field is blank, the cmdlet doesn’t return data (it's the
Set-CASMailbox
case).
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.
Related videos on Youtube
Sonnenbiene
Updated on September 18, 2022Comments
-
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" }