Reputation: 1305
I'm writing a script that will be run remotely against my mail server using something similar to:
$credentials = Get-Credential
$session = New-PSSession `
-ConnectionUri http://mailserver/PowerShell/ `
-Authentication Kerberos `
-ConfigurationName Microsoft.Exchange `
-Credential $credentials
$module = Import-PSSession $session
I will be receiving the recipient name from the user via read-host, parameter or pipeline, so I would like my script to bail out if the recipient is not valid and get-recipient is not successful. The -ErrorAction seemed like a logical choice for this.
get-recipient "doesnotexist" -ErrorAction SilentlyContinue; write-host "will output";
get-recipient "doesnotexist" -ErrorAction Stop; write-host "will output"
get-recipient "doesnotexist" -ErrorAction Inquire; write-host "will not output if halt selected, otherwise displayed"
according to get-help about_CommonParameters, -EA should modify behavior of non-terminating errors. Here I have a non-terminating error, that I would like to handle by... terminating. I know that EA is having some effect because I get the desired result (interactively) by setting it to "Inquire". What I would like is to terminate without interaction so I can try/catch it.
Upvotes: 0
Views: 2966
Reputation: 343
Just troubleshooted this for the good part of 3 hours. As I was inching closer to a solution, this seemed to be a scope bug when remoting and importing Exchange sessions. I might be mistaken. However, here is a blog with a solution to it, which at the same time confirms my suspicion.
http://rehle.blogspot.dk/2014/11/exchange-remote-sessions.html .... in short, for those that would like to avoid opening the link or in case the link gets taken down:
Use the below in a script that uses Exchange cmdlets from an imported Exchange PS Session:
$saved=$global:ErrorActionPreference
$global:ErrorActionPreference='stop'
Try {
$box = get-mailbox nonexistent -ErrorAction Stop
}
Catch {
"Mailbox was not found"
}
Finally {
$global:ErrorActionPreference=$saved
}
I hope it helps and can help someone else. Holla :-D
Upvotes: 1
Reputation: 18747
Use -ErrorAction Stop
for this.
get-recipient "doesnotexist" -ErrorAction Stop; write-host "will not output"
Upvotes: 1