Reputation: 195
I'm writing a program to create an AD account and enable an Exchange mailbox and I'm getting some strange behaviour from it.
First, although it creates an AD user successfully, the mailbox cannot be enabled because "MyPath/Mr. Example could not be found". I assume this is because of a time lag between the AD server and the Exchange server (the code is run on the Exchange server). While inserting a sleep period seems to fix this, is there any other possibility I may be missing?
Second, I get this error message in the "red error text" that Powershell uses. It seems that my try/catch statement is letting the error slip by, which causes my script to erroneously inform me that the task completed successfully. How could I force the error to be caught within the script rather than being displayed on the console? (I was running it dot-sourced during testing, which is how I noticed this.)
I've included the relevant parts below. Any help is appreciated! Thanks =)
Import-Module ActiveDirectory
Add-PSSnapin Microsoft.Exchange.Management.Powershell.Admin
$errorLog = @()
$masterLog = @()
$time = Get-Date
New-ADUser -SamAccountName "example" -Name "Mr. Example" -Path "DC=MyPath" -Enabled 1 -Server ADServer
try{
Enable-Mailbox -Identity "MyPath/Mr. Example" -Alias "example" -Database "DatabaseName"
}
catch{
$myError = $Error[0]
$errorLog = $errorLog + "[$time] Error enabling mailbox for $fullName`: $myError"
}
if($errorLog.length -eq 0){
echo "An Active Directory account and Exchange mailbox for Mr. Example has been successfully created!"
}
else{
foreach($event in $errorLog){
$masterLog = $masterLog + $event
}
}
Upvotes: 0
Views: 280
Reputation: 200193
There are terminating and non-terminating errors in PowerShell. Only the former are caught by try..catch
. You can force errors to be terminating by setting
... -ErrorAction Stop
for a specific command, or
$ErrorActionPreference = Stop
for the entire script. See the Scripting Guy blog for more information.
Upvotes: 2