Connect-MsolService -EA stop

I am trying to stop my script if my connection to O365 fails with -EA Stop but not having any luck so far.

my code

Try {
                Write-Verbose 'Connecting to $MSOLServer'
                # Create the session to MSOLServer
                $S = New-PSSession -ComputerName $MSOLServer -Credential $MSOLServerCredImport -EA Stop
                # Import the O365 cmdlet on the $MSOLServer
                Invoke-Command -Session $S {Import-Module MSOnline} -EA stop
                # Export the $MSOLServer cmdlet from remote to local powershell instance
                Import-PSSession -Session $S -Module MSOnline -AllowClobber -EA Stop
                # Connect to MSOnline
                Connect-MsolService -Credential $MSOLOnlineCredImport -EA stop
            } Catch {
                Write-Verbose 'Cant connect to O365 server or O365'
                # If we are logging write it to the log
                if ($Log) {
                    'Cant connect to O365 server or O365' | Out-File $ErrorLogFile_FP -Append
                    # Pull back some of the detaill PS errors for the logs
                    "$_" | Out-File $ErrorLogFile_FP -Append
                }
                # If the connection fails there is no point in continuing
                Write-Verbose 'Cant continue without a session so bye bye'
                If ($log) {
                    'Cant continue without a session so bye bye' | Out-File $ErrorLogFile_FP -Append
                }
                Exit
            }   

The -EA Stop works on all lines apart from

Connect-MsolService -Credential $MSOLOnlineCredImport -EA stop

If I pass the wrong credentials I get the error

Unable to authenticate your credentials. Make sure that your user name is in the format: @. If this issue persists, contact Support.
+ CategoryInfo : OperationStopped: (:slight_smile: [Connect-MsolService], MicrosoftOnlineException
+ FullyQualifiedErrorId : 0x80048862,Microsoft.Online.Administration.Automation.ConnectMsolService

But the script continues rather than dropping into the catch and then exiting the script

anyone else have the same problem?

It’s possible the cmdlet isn’t throwing a terminating exception that PowerShell can actually catch. That’s unfortunately a cmdlet decision decision and not necessarily something you can work around, unfortunately. I’m a bit surprised that New-PSSession isn’t barfing when you pass a bad credential.

Are you sure New-PSSession works with an incorrect credential, but doesn’t toss an exception?

try catch works for me. It’s really simple to not execute following code in powershell by setting a random variable and testing the condition.

Try{

Connect-MsolService -Credential $credentials}

Catch{
$e -eq $true}

if($e -ne $true){‘rest of code’}

This is exactly how I do it although I don’t worry about executing the rest of the code as it won’t do anything anyways.

Try{

Connect-MsolService -Credential $credentials}

Catch{

write-eventlog -LogName “O365 User Script” -Source “O365 User Script” -EventId 55559 -EntryType Error -Category 0 -Message “Could not connect to MSOLService”}

Don,

-EA stop works for the lines

$S = New-PSSession -ComputerName $MSOLServer -Credential $MSOLServerCredImport -EA Stop
Invoke-Command -Session $S {Import-Module MSOnline} -EA Stop
Import-PSSession -Session $S -Module MSOnline -AllowClobber -EA Stop

its only the connect-msolservice i am having problems with

Connect-MsolService -Credential $MSOLOnlineCredImport -EA Stop

perhaps, as you say, that the error is not catch-able. But if others can get it to work I will keep looking.

Dan,
since my connect-msol line never seems to drop into the catch loop I cant change a value there.

Cheers.

sorry I used -eq when it should have been =, I always do that:-)

Try{

Connect-MsolService -Credential $credentials -ea ‘stop’}

Catch{
$e = $true}

In case anyone else comes across this, I never go it working so I am doing this as a work around. Connect up to O365 then,

# Because -EA stop is not working. Try a MSOL command if it fails assume there has been a problem and exit
        $CheckO365 = Get-MsolDomain -EA SilentlyContinue
        if ($CheckO365) {
            # Connected to O365
            Write-Verbose 'Connected to O365'
        } else {
            Write-Verbose 'Cant connect to O365 server or O365'
            # If we are logging write it to the log
            # If the connection fails there is no point in continuing
            Write-Verbose 'Cant continue without a session so bye bye'
            Exit
        }

I don’t know why you’re not catching an error. This is what I get when I enter a bad password.

PS H:> Connect-MsolService -Credential $credentials -ea ‘stop’
Connect-MsolService : Exception of type ‘Microsoft.Online.Administration.Automation.MicrosoftOnlineException’ was
thrown.
At line:1 char:1

  • Connect-MsolService -Credential $credentials -ea ‘stop’
  •   + CategoryInfo          : OperationStopped: (:) [Connect-MsolService], MicrosoftOnlineException
      + FullyQualifiedErrorId : 0x800488F2,Microsoft.Online.Administration.Automation.ConnectMsolService
    
    

PS H:> $error[0]
The running command stopped because the preference variable “ErrorActionPreference” or common parameter is set to
Stop: Exception of type ‘Microsoft.Online.Administration.Automation.MicrosoftOnlineException’ was thrown.

Seeing there has been no answer to this problem.

I tried getting this to work, first it did not work, after some adjustment and trial and error, I cam up with the following, which works for me:

    #----- Define Admin Credential Variables -----# 
$AdminUsername = "" 
    $AdminPassword = ""
    $AdminSecurePassword = ConvertTo-SecureString -String "$AdminPassword" -AsPlainText -Force
    $AdminCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $AdminUsername,$AdminSecurePassword

        #----- Connect to Microsoft Online Services -----#
    Write-host "Connecting to Microsoft Online Services" -ForegroundColor Yellow
Try {
    $ConnectMsol = Connect-MsolService -Credential $AdminCredential -EA Stop
        Write-Host "Connected to the Microsoft Online Services" -ForegroundColor Green
} Catch {
    $ErrorMessage = $_.Exception.Message
    $FailedItem = $_.Exception.ItemName
    Write-Host "Error message: $ErrorMessage" -ForegroundColor Black -BackgroundColor Red
    Write-Host "Script has failed to connect to the Microsoft Online Services with the following credentials:" -ForegroundColor Red
    Write-Host "Username: $AdminUsername" -ForegroundColor White
    Write-Host "Password: $AdminPassword" -ForegroundColor White
    Break
}

Output with correct credentials:
PS C:\Windows\system32> \tsclient\R\BORG\Powershell scripts\Permanent Delete MS Office User Account.ps1
Connecting to Microsoft Online Services
Connected to the Microsoft Online Services

Output with incorrect credentials:
PS C:\Windows\system32> \tsclient\R\BORG\Powershell scripts\Permanent Delete MS Office User Account.ps1
Connecting to Microsoft Online Services
Error message: The user name or password is incorrect. Verify your user name, and then type your password again.
Script has failed to connect to the Microsoft Online Services with the following credentials:
Username:
Password: