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
}
Unable to authenticate your credentials. Make sure that your user name is in the format: @. If this issue persists, contact Support.
+ CategoryInfo : OperationStopped: ( [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
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?
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
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.
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: