I’m trying to get some error handling in my scripts and have them stop executing when an error is hit. But seems with these O365 commands it works in the ISE but now when I run from the console. Any help/direction would be appreciated.
Connecting to the cloud
Function Connect-O365
{
$Creds = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $Creds -Authentication Basic -AllowRedirection
Import-PSSession $Session -AllowClobber
Import-Module Msonline
Connect-MSOLService -credential $creds
}
Connecting to the cloud
Connect-O365
Try
{
$ErrorActionPreference = “Stop”
Do {
Getting mailbox that permissions need to be modified ON
Write-Host -ForegroundColor Green "Enter the email address of the mailbox you want permissions to be granted to or 'q' to quit: " -NoNewline
$Mailbox = Read-Host
If ($mailbox -ne 'q')
{
Getting the user that needs access to the mailbox
Write-Host -ForegroundColor Green "Enter the email address of the user that you want to give permissions to that mailbox: " -NoNewline
$User = Read-Host
Setting the Permissions to the mailbox.
Add-MailboxPermission $Mailbox -User $User -AccessRights FullAccess -InheritanceType All -ErrorAction Stop
Allowing option to set Send As Permissions
Write-Host -ForegroundColor Green "Do you want the user to have right to send as the users mailbox as well? Y/N: " -NoNewline
$SendAsAccess = Read-Host
If ($SendAsAccess -eq 'Y')
{
Add-RecipientPermission $Mailbox -Trustee $User -AccessRights SendAs -ErrorAction Stop
}
Getting details to verify results
$results = Get-MailboxPermission $Mailbox | Select User, AccessRights
Writing results to screen
Write-Host -ForegroundColor Magenta "These are the users that have access to this mailbox and their access level: " -NoNewline
$results
}
} Until ($mailbox -eq “q”)
}
Catch [system.exception]
{
Write-Host "Operation Failed. Find the Error Message below:" -ForegroundColor Red
Write-Host $_.Exception.Message -ForegroundColor Red
pause
}
Finally
{
#Reset the Error Action to Default
$ErrorActionPreference = “Continue”
}