Exchange anagement Shell catch enable-mailbox error - powershell

I have script that creates user accounts and establishes an e-mail address for those accounts. All 'create-commands' are surrounded by a try/catch block to catch errors and add a message to the output log. This works fine... except for the enable-mailbox command
try {
Enable-Maibox (.. parameters ...)
}
catch {
$errorsEncountered = $true
Write-Output "Error establishing e-mail address for $($UserData.username)"
}
when the enable-mailbox command fails... the catch-part is skipped. Why is this? And how can I fix this?

Non-termineting errors are not catched. Use '-ErrorAction Stop' to make the errors terminating errors.
Enable-Maibox (.. parameters ...) -ErrorAction Stop

I could be wrong but "Enable-Maibox" looks mis-spelled.

Related

Powershell try block not working on VSTS build

I'm running a command in Powershell through VSTS to affect Azure. The command works, but it gives an error after. The params and connection are working as evidenced by the fact that the group gets permission from the command. I figure a workaround is to put the command in a try block, have it run, and then when the error comes up go to the catch block and end without throwing the error.
When I run this script, I still get the same error, like the try block is ignored. Do I have the syntax wrong?
Try
{
New-AzureRmRoleAssignment -ObjectId "xxxx" -RoleDefinitionName $roleName -ResourceGroupName pentest-$featureName
}
Catch
{
Write-Output "Whoops"
}
Edit: I added $ErrorActionPreference = "Stop" before the try-block and it caught the error properly.
The try block was ignored because of the wrong $ErrorActionPreference. Changing it from "Continue" to "Stop" fixed it.

Power Shell Error Trapping

I can't figure out why powershell will not trap errors when running a script against office365 (Exchange online). I receive the raw error message each time, despite my try and catch blocks.
Foreach ($groups in $groups)
{
try
{
Add-DistributionGroupMember "$Groups" -Member "$UserName" -BypassSecurityGroupManagerCheck -ErrorAction Stop
#write-host "Added user $userName to $Groups";
}
Catch
{
Write-Output "`t $userName is already a member of $Groups."
}
}
Having the same issue here. We're seeing the error block but not the custom error message in the catch.
I need to trap when users can't be added (couldn't find the user) or any other specific error and dump these accounts to a CSV file...
EDIT:
Of course the moment I post this I find the answer... Adding -ErrorAction STOP makes it work properly, otherwise it simply shows the message and I guess doesn't return an errorcode... The actual message can be caught using this Catch
Catch{
Echo $User $_.exception.Message
}

try, catch doesent seem to work

I have the following code which I thought would allow me to catch an error and instead of generating the error write out "An Error Occurred".
Unfortunately, it still shows the error "Failed to restart the computer: Access is denied" instead.
I know why this is happening but I want to be able to catch the error and reformat it. What am I doing wrong?
try {
Restart-Computer -ComputerName MFG-KY-PC74 -Force
} catch {
Write-Host "An Error Occurred"
}
In PowerShell there are terminating and non-terminating errors. The former terminate script execution (if not caught) and can be caught by try..catch, the latter don't terminate script execution (so there's nothing to catch). The error you're receiving is a non-terminating one, so you need to make it a terminating error by appending -ErrorAction Stop to the statement:
try {
Restart-Computer -ComputerName MFG-KY-PC74 -Force -ErrorAction Stop
} catch {
write-host "An Error Occurred"
}
Alternatively you can set $ErrorActionPreference = "Stop" if you want all errors to become terminating errors.
See this article on the Scripting Guy blog for more information.

Powershell Try Catch invoke-sqlcmd

I am having problems catching an error in PowerShell when a connection fails to a SQL Server using Invoke-Sqlcmd. This is some generic code to demonstrate the issue:
CLS
$server = "Localhost\fake"
try
{
Invoke-Sqlcmd -Query "SELECT DB_NAME() as [Database]" -Server $server
}
catch
{
Write-Host "Error connecting to server " $server
}
I get the following error:
Invoke-Sqlcmd : A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name
is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I was expecting to get the one line statement: "Error connecting to server Localhost\fake"
It would appear that error is considered non-terminating which is a bit odd. Try the Invoke-SqlCommand with an additional parameter: -ErrorAction Stop. If there error is non-terminating, this will convert it to a terminating error that you can catch.
Posting additional info to supplement the answer by #KeithHill as an answer since it is too long for a comment.
If the error record was created by the Write-Error commandlet it is non-terminating and subject to the behavior specified by the -ErrorAction argument or the $ErrorActionPreference system variable. Errors using throw are terminating. See the documentation for Write-Error (Note that PowerShell 4.0 and below do not have the -Exception parameter mentioned in the web page.) and about_Throw in the PowerShell help system.
If you want to add custom error information and make it a terminating error, throw from your catch block as follows:
catch
{
throw (New-Object System.Exception "Error connecting to server $($server).", $_.Exception)
}
You can use Write-Error if you want termination to behave as specified by the -ErrorAction argument. In PowerShell 4.0 and below the Write-Error commandlet does not allow a -Exception argument and therefore will not provide an InnerException. That means that the caller would have to examine the collection in the $Error system variable if it needs to determine the original exception. In later versions you can Use Write-Error -Message "Some additional error information." -Exception $_.Exception in your catch block.
Try
CLS
$server = "Localhost/fake"
try
{
Invoke-Sqlcmd -Query "SELECT DB_NAME() as [Database]" -Server $server
}
catch
{
$_ | Out-Null
Write-Host "Error connecting to server " $server
}
This will capture the error and redirect it to null and display your write-host

Using try/catch blocks with Lync 2010 cmdlets in powershell

I've written a function to wrap the the new-cssipdomain cmdlet with a try/catch block incase the sip domain already exists.
Code is:
function LHP-AddSIPDomain
{
param ( [string] $SIPDomain)
try
{
New-cssipdomain -id $SIPDomain
}
catch
{
Write-host "Lync specific exception occured adding SIP domain"
Write-host "Exception String:"+$_.Exception.Message
exit
}
}
LHP-AddSIPDOmain -SipDomain "Test206.com"
The output when the domain already exists is:
New-CsSipDomain : "SipDomain" with identity "Test206.com" already exists. To modify
the existing item, use the Set- cmdlet. To create a new item, use a different
identity. Parameter name: Identity
At S:\Scripts\LHP-AddSIPDomain.ps1:33 char:26
+ New-cssipdomain <<<< -id $SIPDomain
+ CategoryInfo : InvalidArgument: (Test206.com:String) [New-CsSipDomain],
ArgumentException
+ FullyQualifiedErrorId :
InvalidIdentity,Microsoft.Rtc.Management.Xds.NewOcsSipDomainCmdlet
This should be caught by the try/catch block.
I've tried adding the [system.exception] to the catch statement. I'ev also tried setting $erroraction=”Stop”. Neither made any different, the try/catch statement seems to be being ignored. I've used this type of code structure to capture errors from the new-aduser cmdlet and this seemed to work ok.
I have also considerd and tried using hte get-cssipdomin cmdlet first to check if the sip domain already exists, but I have a similar problem in that if you call get-cscsipdomain with a domain that doesn't exist it throws an error which I don't seem to be able to catch.
Any suggestions would be greatly appreciated.
TRY:
try
{
New-cssipdomain -id $SIPDomain -ERRORACTION SilentlyContinue
}
Maybe the command it self got a try/catch for errors.
You can perhaps have a look to this answer. It explains why try/catch is sometime not working.
Can't you just write :
$Res = New-cssipdomain -id $SIPDomain -ERRORACTION SilentlyContinue
And test the value of $Res ?
I guess the error you get is not a terminating error and that's why you can't catch it. Try to set the ErrorAction value to 'stop', that will make the error a terminating error and you'll be able to catch it in the catch block.