Question

I am working in PowerShell 2.0 on a olSync server connected to live@edu. I am trying to use a try/catch statement.

In order to run on the live@edu server we have to run a script that uses a Import-PSSession command.

My problem that I am having is that the try/catch statement works perfectly before I connect to the other session but after I connect the errors aren't caught and are displayed like they would normally.

(what I mean by working perfectly is that they don't show up and my more user friendly response shows)

What am I missing? Do I simply not understand the PSSession command enough?

Code for connecting (for obvious reasons I did not include the credentials)

$Session = New-PSSession -ConfigurationName Microsoft.Exchange 
           -ConnectionUri https://ps.outlook.com/powershell/ -Credential $LiveCred 
          -Authentication Basic -AllowRedirection  

Import-PSSession $Session

Example code that I am testing

$count = 0  
$name = "quit"  
$x  

do  
{   
try    
{  
    $name = Read-Host 'What is the username?'  
    $x = get-mailbox $name  
    write-host $x  
}  
catch  
{  
       Write-Host "Oh No!`n $error[0].exception"  
       $count++  
}  
}  
while ($name -ne "quit")  

write-host "$count errors happened"  

Output When connected

What is the username?: test  
test, test  

What is the username?: test2  
The operation couldn't be performed because object 'test2' couldn't be found on ...  

What is the username?: quit  
The operation couldn't be performed because object 'quit' couldn't be found on ...  

0 errors happened  
test  

.
Output When Not Connected

What is the username?: test
Oh No!
The term 'get-mailbox' is not recognized as the name of a cmdlet, function, script file, > or operable program. Check the spelling of the name, or if a path was included, verify
that the path is correct and try again. The term 'get-mailbox'
is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the
path is correct and try again.[0].exception

Was it helpful?

Solution

The error you are getting is probably a non terminating error and try..catch only catches terminating erros. The solution is turning all errors in terminating errors. This can be done by using the ErrorAction parameter or by setting it for your script with $ErrorActionPreference = 'Stop'

$x = get-mailbox $name -ErrorAction Stop

See here and here and here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top