Forum / Remote Desktop Manager - Macro/Script/Tools

Connecting to Office 365 Powershell

  • Create an Issue
  • Cancel

Hello,

What RDM version are you using?

Have you already tried with an account with MFA enabled? If so, are you experiencing any issue?

Best regards,



Érica Poirier

signaturesignature

Clock2 mths

Hi epoirier,


Using free edition as of the moment version 2019.2.18.0.
Have try the script but when I press execute it ask me what session to choose but don't know. Also can't find the allow password in variable.


image


Best Regards,
Mark

Clock2 mths


Hello Mark,

You can find the Allow password in variable option in the Security Settings tab of the PowerShell entry.

image

As I cannot see your image in your last post, what PowerShell entry type are you using? Is it the PowerShell session entry (PowerShell blue icon) or the PowerShell Macro/Script/Tool (green icon)?

image

Best regards,



Érica Poirier

signaturesignature

Clock2 mths

Hi Erica,

It now works but it asked me to login, is there a way it will auto fill the username and password so it can reach MFA window and skip the username and password?

Best Regards,
Mark

Screenshot_156.png
Clock2 mths


Hi Erica,

How to bypass Self Signed Certs? it doesn't work with Chrome but I made it work with IE.

Best Regards,
Mark


mard wrote:

Hi Erica,

It now works but it asked me to login, is there a way it will auto fill the username and password so it can reach MFA window and skip the username and password?

Best Regards,
Mark

Clock2 mths

Hello Mark,

Could you please send me the PowerShell script entry to investigate why it doesn't properly send the credentials? Please send it to ticket@devolutions.net to open a ticket in our system.

Best regards,



Érica Poirier

signaturesignature

Clock2 mths

Hi Erica,

Kindly see below.


#Created by Reinout.Dorreboom@bevio.nl, edited by Jeffrey Veenhuis
$User = 'myusername@username.com'
$PWord = 'mypassword'
$Password = ConvertTo-SecureString -String $PWord -AsPlainText -Force
$creds = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $PassWord

#Clean up opened sessions
Write-Host 'Clean up the current sessions on the computer...' -BackgroundColor Black -ForegroundColor Cyan -NoNewline
Get-PSSession | Remove-PSSession
Write-Host 'Done' -BackgroundColor Black -ForegroundColor Green

$Modules = @("MSOnline","SkypeOnlineConnector")

$Modules | foreach{
if (Get-Module -ListAvailable -Name MSOnline) {
Write-Host "$_ Module exists" -ForegroundColor green
} else {
Write-Host "$_ Module does not exist" -ForegroundColor red
$answer = Read-Host -Prompt "Do you want to continue? Yes (y) / No (n)"
If($answer -eq "n"){exit}
}
}

#Connect to the MS Online Services
Write-Host 'Connecting to MS Online Services...' -BackgroundColor Black -ForegroundColor Cyan -NoNewline
Connect-MsolService –Credential $Creds |Out-Null
Write-Host 'Done' -BackgroundColor Black -ForegroundColor Green

#Login to Exchange Online Remote Powershell and import the MS Exchange Module
Write-Host 'Connecting to Exchange Online...' -BackgroundColor Black -ForegroundColor Cyan -NoNewline
$ExOnSession = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $Creds -Authentication Basic -AllowRedirection -WarningAction SilentlyContinue
Import-PSSession $ExOnSession -WarningAction SilentlyContinue -DisableNameChecking |Out-Null
Write-Host 'Done' -BackgroundColor Black -ForegroundColor Green

#Login to the Compliance Center Remote Powershell and import the Compliance center Module
Write-Host 'Connecting to the Compliance Center...' -BackgroundColor Black -ForegroundColor Cyan -NoNewline
$ComplianceSession = New-PSSession –ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $Creds -Authentication Basic -AllowRedirection -WarningAction SilentlyContinue
Import-PSSession $ComplianceSession -WarningAction SilentlyContinue -DisableNameChecking |Out-Null
Write-Host 'Done' -BackgroundColor Black -ForegroundColor Green

Write-Host "`nYou are now connected to Office 365, Exchange Online, the Compliance center and Skype for Business Online" -BackgroundColor Black -ForegroundColor Yellow

Best Regards,
Mark

Clock2 mths

Hello,

Could you please try to replace the value of the 2 variables $user and $PWord with the following value to see if it will help to send the credentials? By using the RDM variables $USERNAME$ and $PASSWORD$, it should use the credential set on the entry that is running the PowerShell script.

$User = $USERNAME$
$PWord = $PASSWORD$
$Password = ConvertTo-SecureString -String $PWord -AsPlainText -Force
$creds = New-Object –TypeName System.Management.Automation.PSCredential –ArgumentList $User, $PassWord

Best regards,



Érica Poirier

signaturesignature

Clock2 mths

Hi Erica,

I'm encountering now this.


myemailaddress.com : The term 'myemailaddress.com' 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.
At C:\Users\user\AppData\Local\Temp\RDM\81a88f87-7833-4382-a587-476992faed94.ps1:2 char:9
+ $User = myemailaddress.com
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (myemailaddress.com:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

mypassword : The term 'mypassword' 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.
At C:\Users\user\AppData\Local\Temp\RDM\81a88f87-7833-4382-a587-476992faed94.ps1:3 char:10
+ $PWord = mypassword
+ ~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (mypassword:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

ConvertTo-SecureString : Cannot bind argument to parameter 'String' because it is null.
At C:\Users\user\AppData\Local\Temp\RDM\81a88f87-7833-4382-a587-476992faed94.ps1:4 char:44
+ $Password = ConvertTo-SecureString -String $PWord -AsPlainText -Force
+ ~~~~~~
+ CategoryInfo : InvalidData: (smile [ConvertTo-SecureString], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand

New-Object : Exception calling ".ctor" with "2" argument(s): "Cannot process argument because the value of argument "userName" is not valid. Change the value of the "userName" argument and
run the operation again."
At C:\Users\user\AppData\Local\Temp\RDM\81a88f87-7833-4382-a587-476992faed94.ps1:5 char:10
+ $creds = New-Object -TypeName System.Management.Automation.PSCredenti ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (smile [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

Clean up the current sessions on the computer...Done
MSOnline Module exists
SkypeOnlineConnector Module exists
Connecting to MS Online Services...Connect-MsolService : Authentication Error: Unexpected authentication failure.
At C:\Users\user\AppData\Local\Temp\RDM\81a88f87-7833-4382-a587-476992faed94.ps1:26 char:1
+ Connect-MsolService -Credential $Creds |Out-Null
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (smile [Connect-MsolService], Exception
+ FullyQualifiedErrorId : System.Exception,Microsoft.Online.Administration.Automation.ConnectMsolServ
ice

Done
Connecting to Exchange Online...New-PSSession : Cannot bind argument to parameter 'Credential' because it is null.
At C:\Users\user\AppData\Local\Temp\RDM\81a88f87-7833-4382-a587-476992faed94.ps1:31 char:144
+ ... //outlook.office365.com/powershell-liveid/ -Credential $Creds -Authen ...
+ ~~~~~~
+ CategoryInfo : InvalidData: (smile [New-PSSession], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Command
s.NewPSSessionCommand

Import-PSSession : Cannot validate argument on parameter 'Session'. The argument is null. Provide a valid
value for the argument, and then try running the command again.
At C:\Users\user\AppData\Local\Temp\RDM\81a88f87-7833-4382-a587-476992faed94.ps1:32 char:18
+ Import-PSSession $ExOnSession -WarningAction SilentlyContinue -Disabl ...
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (smile [Import-PSSession], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.ImportPSSess
ionCommand

Done
Connecting to the Compliance Center...New-PSSession : Cannot bind argument to parameter 'Credential' because it is null.
At C:\Users\user\AppData\Local\Temp\RDM\81a88f87-7833-4382-a587-476992faed94.ps1:37 char:165
+ ... .protection.outlook.com/powershell-liveid/ -Credential $Creds -Authen ...
+ ~~~~~~
+ CategoryInfo : InvalidData: (smile [New-PSSession], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Command
s.NewPSSessionCommand

Import-PSSession : Cannot validate argument on parameter 'Session'. The argument is null. Provide a valid
value for the argument, and then try running the command again.
At C:\Users\user\AppData\Local\Temp\RDM\81a88f87-7833-4382-a587-476992faed94.ps1:38 char:18
+ Import-PSSession $ComplianceSession -WarningAction SilentlyContinue - ...
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (smile [Import-PSSession], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.ImportPSSess
ionCommand

Done

You are now connected to Office 365, Exchange Online, the Compliance center and Skype for Business Online

Best Regards,
Mark

Clock2 mths


Hello,

The first two errors are related to missing quotes. $User = myemailaddress.com should be $User = "myemailaddress.com" and $PWord = "mypassword" should be $PWord = "mypassword". Fixing those two issues should help to get the script running.

Best regards,



Érica Poirier

signaturesignature

Clock2 mths

Hi Erica,

Now it is going here in this part it is manual?

Best Regards,
Mark

Screenshot_161.png
Screenshot_162.png
Clock2 mths

Hello,

Have you set your credentials information in the PowerShell entry?

If so, please try to use the RDM variables like the following and let me know if this is working.

$User = "$USERNAME$"
$PWord = "$PASSWORD$"

Please note that you need to enable the Allow password in variable option in the Security Settings tab.

image

Best regards,



Érica Poirier

signaturesignature

Clock2 mths

Hi Erica,

Already did, Kindly see screen grab.


Best Regards,
Mark

Screenshot_169.png
Screenshot_168.png
Clock30 days

Hello,

It will be important to also use the RDM variables in your PowerShell script to get it working.

Have you replaced the username and the password value like the following?

$User = "$USERNAME$"
$PWord = "$PASSWORD$"

Best regards,



Érica Poirier

signaturesignature

Clock30 days

Hi Erica,

Have already confirmed it is
$User = "$USERNAME$"
$PWord = "$PASSWORD$"


Here is what I encountered.



Clean up the current sessions on the computer...Done
MSOnline Module exists
SkypeOnlineConnector Module exists
Connecting to MS Online Services...Done
Connecting to Exchange Online...New-PSSession : [outlook.office365.com] Connecting to remote server outlook.office365.com failed with the following error message : Access is denied. For more information, see the
about_Remote_Troubleshooting Help topic.
At C:\Users\mard\AppData\Local\Temp\RDM\63207b1e-7903-4608-ae85-4d65ab2bdc5a.ps1:31 char:16
+ ... OnSession = New-PSSession -ConfigurationName Microsoft.Exchange -Conn ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Import-PSSession : Cannot validate argument on parameter 'Session'. The argument is null. Provide a valid value for the argument, and then try running the command again.
At C:\Users\mard\AppData\Local\Temp\RDM\63207b1e-7903-4608-ae85-4d65ab2bdc5a.ps1:32 char:18
+ Import-PSSession $ExOnSession -WarningAction SilentlyContinue -Disabl ...
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (smile [Import-PSSession], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.ImportPSSessionCommand


Done
Connecting to the Compliance Center...New-PSSession : [ps.compliance.protection.outlook.com] Connecting to remote server ps.compliance.protection.outlook.com failed with the following error message : Access is denied. For more
information, see the about_Remote_Troubleshooting Help topic.
At C:\Users\mard\AppData\Local\Temp\RDM\63207b1e-7903-4608-ae85-4d65ab2bdc5a.ps1:37 char:22
+ ... ceSession = New-PSSession -ConfigurationName Microsoft.Exchange -Conn ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Import-PSSession : Cannot validate argument on parameter 'Session'. The argument is null. Provide a valid value for the argument, and then try running the command again.
At C:\Users\mard\AppData\Local\Temp\RDM\63207b1e-7903-4608-ae85-4d65ab2bdc5a.ps1:38 char:18
+ Import-PSSession $ComplianceSession -WarningAction SilentlyContinue - ...
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (smile [Import-PSSession], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.ImportPSSessionCommand


Done


You are now connected to Office 365, Exchange Online, the Compliance center and Skype for Business Online
PS C:\WINDOWS\system32> get-mailbox myemail@email.com get-mailbox : 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.
At line:1 char:1
+ get-mailbox myemail@email.com
+ ~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (get-mailbox:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException


PS C:\WINDOWS\system32> Get-MsolUser -UserPrincipalName myemail@email.com
UserPrincipalName DisplayName isLicensed
----------------- ----------- ----------
myemail@email.com Mark Diaz True


PS C:\WINDOWS\system32>


Best Regards,
Mark

Clock30 days

Hi Mark,

It looks like there is an error with the Get-Mailbox command. Could you have a look at Micorsoft help topic at https://docs.microsoft.com/en-us/powershell/module/exchange/mailboxes/get-mailbox?view=exchange-ps ?

Regards,



David Grandolfo

signaturesignature

Clock26 days

Hi David,

I can connect to exchange online without issue on my powershell, not sure with the script provided on this thread I can't. and it won't auto login on the Azure portion.

Best Regards,
Mark

Screenshot_172.png
Clock25 days

Hi Mark,

I think the Get-Mailbox error that you get when you start the script is a cause that Office 365 PowerShell commands are not loaded. You need to add a line that will load them.

Do you need help with this?

Regards,



David Grandolfo

signaturesignature

Clock12 days

@David,

Yes please, also does the login for MFA should be manual?

Best Regards,
Mark

Clock12 days

Hi,

After looking again to the PowerShell script I see that you miss some access to perform the proper command.

Could you confirm the error bellow:
Connecting to Exchange Online...New-PSSession : [outlook.office365.com] Connecting to remote server outlook.office365.com failed with the following error message: Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.


It's also possible that the script you provide us is deprecated if it's the one written by a customer in this thread, the script has at least 3 years.

Before we continue the diagnostic in RDM, could you confirm if the script works well outside of RDM?

Best regards,



David Grandolfo

signaturesignature

Clock10 days

Here's the script we're currently using, def less convient then without MFA but better then nothing.

#region Connect-Office365
function Connect-Office365
{
<#
.NOTES
===========================================================================
Created on: 2/4/2019 10:42 PM
Created by: Bradley Wyatt
E-Mail: Brad@TheLazyAdministrator.com
GitHub: https://github.com/bwya77
Website: https://www.thelazyadministrator.com
Organization: Porcaro Stolarek Mete Partners; The Lazy Administrator
Filename: Connect-Office365.ps1
Version: 1.0.4
Contributors: /u/Sheppard_Ra
Changelog:
1.0.4
- Host title will add a service or services you are connected to. If unable to connect it will not display connection status until connection is valid
===========================================================================
.SYNOPSIS
Connect to Office 365 Services
.DESCRIPTION
Connect to different Office 365 Services using PowerShell function. Supports MFA.
.PARAMETER MFA
Description: Specifies MFA requirement to sign into Office 365 services. If set to $True it will use the Office 365 ExoPSSession Module to sign into Exchange & Compliance Center using MFA. Other modules support MFA without needing another external module
.PARAMETER Exchange
Description: Connect to Exchange Online
.PARAMETER SkypeForBusiness
Description: Connect to Skype for Business
.PARAMETER SharePoint
Description: Connect to SharePoint Online
.PARAMETER SecurityandCompliance
Description: Connect to Security and Compliance Center
.PARAMETER AzureAD
Description: Connect to Azure AD V2
.PARAMETER MSOnline
Type: Switch
Description: Connect to Azure AD V1
.PARAMETER Teams
Type: Switch
Description: Connect to Teams
.EXAMPLE
Description: Connect to SharePoint Online
C:\PS> Connect-Office365 -SharePoint
.EXAMPLE
Description: Connect to Exchange Online and Azure AD V1 (MSOnline)
C:\PS> Connect-Office365 -Service Exchange, MSOnline
.EXAMPLE
Description: Connect to Exchange Online and Azure AD V2 using Multi-Factor Authentication
C:\PS> Connect-Office365 -Service Exchange, MSOnline -MFA
.EXAMPLE
Description: Connect to Teams and Skype for Business
C:\PS> Connect-Office365 -Service Teams, SkypeForBusiness
.EXAMPLE
Description: Connect to SharePoint Online
C:\PS> Connect-Office365 -Service SharePoint -SharePointOrganizationName bwya77 -MFA
.LINK
Online version: https://www.thelazyadministrator.com/2019/02/05/powershell-function-to-connect-to-all-office-365-services
#>
[OutputType()]
[CmdletBinding(DefaultParameterSetName)]
Param (
[Parameter(Mandatory = $True, Position = 1)]
[ValidateSet('AzureAD', 'Exchange', 'MSOnline', 'SecurityAndCompliance', 'SharePoint', 'SkypeForBusiness', 'Teams')]
[string[]]$Service,
[Parameter(Mandatory = $False, Position = 2)]
[Alias('SPOrgName')]
[string]$SharePointOrganizationName,
[Parameter(Mandatory = $False, Position = 3, ParameterSetName = 'Credential')]
[PSCredential]$Credential,
[Parameter(Mandatory = $False, Position = 3, ParameterSetName = 'MFA')]
[Switch]$MFA
)
$getModuleSplat = @{
ListAvailable = $True
Verbose = $False
}
If ($MFA -ne $True)
{
Write-Verbose "Gathering PSCredentials object for non MFA sign on"
$Credential = Get-Credential -Message "Please enter your Office 365 credentials"
}
ForEach ($Item in $PSBoundParameters.Service)
{
Write-Verbose "Attempting connection to $Item"
Switch ($Item)
{
AzureAD {
If ($null -eq (Get-Module @getModuleSplat -Name "AzureAD"))
{
Write-Error "SkypeOnlineConnector Module is not present!"
continue
}
Else
{
If ($MFA -eq $True)
{
$Connect = Connect-AzureAD
If ($Connect -ne $Null)
{
If (($host.ui.RawUI.WindowTitle) -notlike "*Connected To:*")
{
$host.ui.RawUI.WindowTitle += " - Connected To: AzureAD"
}
Else
{
$host.ui.RawUI.WindowTitle += " - AzureAD"
}
}
}
Else
{
$Connect = Connect-AzureAD -Credential $Credential
If ($Connect -ne $Null)
{
If (($host.ui.RawUI.WindowTitle) -notlike "*Connected To:*")
{
$host.ui.RawUI.WindowTitle += " - Connected To: AzureAD"
}
Else
{
$host.ui.RawUI.WindowTitle += " - AzureAD"
}
}
}
}
continue
}
Exchange {
If ($MFA -eq $True)
{
$getChildItemSplat = @{
Path = "$Env:LOCALAPPDATA\Apps\2.0\*\CreateExoPSSession.ps1"
Recurse = $true
ErrorAction = 'SilentlyContinue'
Verbose = $false
}
$MFAExchangeModule = ((Get-ChildItem @getChildItemSplat | Select-Object -ExpandProperty Target -First 1).Replace("CreateExoPSSession.ps1", ""))
If ($null -eq $MFAExchangeModule)
{
Write-Error "The Exchange Online MFA Module was not found!
https://docs.microsoft.com/en-us/powershell/exchange/exchange-online/connect-to-exchange-online-powershell/mfa-connect-to-exchange-online-powershell?view=exchange-ps"
continue
}
Else
{
Write-Verbose "Importing Exchange MFA Module"
. "$MFAExchangeModule\CreateExoPSSession.ps1"
Write-Verbose "Connecting to Exchange Online"
Connect-EXOPSSession
If ($Null -ne (Get-PSSession | Where-Object { $_.ConfigurationName -like "*Exchange*" }))
{
If (($host.ui.RawUI.WindowTitle) -notlike "*Connected To:*")
{
$host.ui.RawUI.WindowTitle += " - Connected To: Exchange"
}
Else
{
$host.ui.RawUI.WindowTitle += " - Exchange"
}
}
}
}
Else
{
$newPSSessionSplat = @{
ConfigurationName = 'Microsoft.Exchange'
ConnectionUri = "https://ps.outlook.com/powershell/"
Authentication = 'Basic'
Credential = $Credential
AllowRedirection = $true
}
$Session = New-PSSession @newPSSessionSplat
Write-Verbose "Connecting to Exchange Online"
Import-PSSession $Session -AllowClobber
If ($Null -ne (Get-PSSession | Where-Object { $_.ConfigurationName -like "*Exchange*" }))
{
If (($host.ui.RawUI.WindowTitle) -notlike "*Connected To:*")
{
$host.ui.RawUI.WindowTitle += " - Connected To: Exchange"
}
Else
{
$host.ui.RawUI.WindowTitle += " - Exchange"
}
}
}
continue
}
MSOnline {
If ($null -eq (Get-Module @getModuleSplat -Name "MSOnline"))
{
Write-Error "MSOnline Module is not present!"
continue
}
Else
{
Write-Verbose "Connecting to MSOnline"
If ($MFA -eq $True)
{
Connect-MsolService
If ($Null -ne (Get-MsolCompanyInformation -ErrorAction SilentlyContinue))
{
If (($host.ui.RawUI.WindowTitle) -notlike "*Connected To:*")
{
$host.ui.RawUI.WindowTitle += " - Connected To: MSOnline"
}
Else
{
$host.ui.RawUI.WindowTitle += " - MSOnline"
}
}
}
Else
{
Connect-MsolService -Credential $Credential
If ($Null -ne (Get-MsolCompanyInformation -ErrorAction SilentlyContinue))
{
If (($host.ui.RawUI.WindowTitle) -notlike "*Connected To:*")
{
$host.ui.RawUI.WindowTitle += " - Connected To: MSOnline"
}
Else
{
$host.ui.RawUI.WindowTitle += " - MSOnline"
}
}
}
}
continue
}
SecurityAndCompliance {
If ($MFA -eq $True)
{
$getChildItemSplat = @{
Path = "$Env:LOCALAPPDATA\Apps\2.0\*\CreateExoPSSession.ps1"
Recurse = $true
ErrorAction = 'SilentlyContinue'
Verbose = $false
}
$MFAExchangeModule = ((Get-ChildItem @getChildItemSplat | Select-Object -ExpandProperty Target -First 1).Replace("CreateExoPSSession.ps1", ""))
If ($null -eq $MFAExchangeModule)
{
Write-Error "The Exchange Online MFA Module was not found!
https://docs.microsoft.com/en-us/powershell/exchange/exchange-online/connect-to-exchange-online-powershell/mfa-connect-to-exchange-online-powershell?view=exchange-ps"
continue
}
Else
{
Write-Verbose "Importing Exchange MFA Module (Required)"
. "$MFAExchangeModule\CreateExoPSSession.ps1"
Write-Verbose "Connecting to Security and Compliance Center"
Connect-IPPSSession
If ($Null -ne (Get-PSSession | Where-Object { $_.ConfigurationName -like "*Exchange*" }))
{
If (($host.ui.RawUI.WindowTitle) -notlike "*Connected To:*")
{
$host.ui.RawUI.WindowTitle += " - Connected To: Security and Compliance Center"
}
Else
{
$host.ui.RawUI.WindowTitle += " - Security and Compliance Center"
}
}
}
}
Else
{
$newPSSessionSplat = @{
ConfigurationName = 'Microsoft.SecurityAndCompliance'
ConnectionUri = 'https://ps.compliance.protection.outlook.com/powershell-liveid/'
Authentication = 'Basic'
Credential = $Credential
AllowRedirection = $true
}
$Session = New-PSSession @newPSSessionSplat
Write-Verbose "Connecting to SecurityAndCompliance"
Import-PSSession $Session -DisableNameChecking
If ($Null -ne (Get-PSSession | Where-Object { $_.ConfigurationName -like "*Exchange*" }))
{
If (($host.ui.RawUI.WindowTitle) -notlike "*Connected To:*")
{
$host.ui.RawUI.WindowTitle += " - Connected To: Security and Compliance Center"
}
Else
{
$host.ui.RawUI.WindowTitle += " - Security and Compliance Center"
}
}
}
continue
}
SharePoint {
If ($null -eq (Get-Module @getModuleSplat -Name Microsoft.Online.SharePoint.PowerShell))
{
Write-Error "Microsoft.Online.SharePoint.PowerShell Module is not present!"
continue
}
Else
{
If (-not ($PSBoundParameters.ContainsKey('SharePointOrganizationName')))
{
Write-Error 'Please provide a valid SharePoint organization name with the -SharePointOrganizationName parameter.'
continue
}
$SharePointURL = "https://{0}-admin.sharepoint.com" -f $SharePointOrganizationName
Write-Verbose "Connecting to SharePoint at $SharePointURL"
If ($MFA -eq $True)
{
$SPOSession = Connect-SPOService -Url $SharePointURL
If ($Null -ne (Get-SPOTenant))
{
If (($host.ui.RawUI.WindowTitle) -notlike "*Connected To:*")
{
$host.ui.RawUI.WindowTitle += " - Connected To: SharePoint Online"
}
Else
{
$host.ui.RawUI.WindowTitle += " - SharePoint Online"
}
}
}
Else
{
$SPOSession = Connect-SPOService -Url $SharePointURL -Credential $Credential
If ($Null -ne (Get-SPOTenant))
{
If (($host.ui.RawUI.WindowTitle) -notlike "*Connected To:*")
{
$host.ui.RawUI.WindowTitle += " - Connected To: SharePoint Online"
}
Else
{
$host.ui.RawUI.WindowTitle += " - SharePoint Online"
}
}
}
}
continue
}
SkypeForBusiness {
Write-Verbose "Connecting to SkypeForBusiness"
If ($null -eq (Get-Module @getModuleSplat -Name "SkypeOnlineConnector"))
{
Write-Error "SkypeOnlineConnector Module is not present!"
}
Else
{
# Skype for Business module
Import-Module SkypeOnlineConnector
If ($MFA -eq $True)
{
$CSSession = New-CsOnlineSession
Import-PSSession $CSSession -AllowClobber
If ($Null -ne (Get-CsOnlineDirectoryTenant))
{
If (($host.ui.RawUI.WindowTitle) -notlike "*Connected To:*")
{
$host.ui.RawUI.WindowTitle += " - Connected To: Skype for Business"
}
Else
{
$host.ui.RawUI.WindowTitle += " - Skype for Business"
}
}
}
Else
{
$CSSession = New-CsOnlineSession -Credential $Credential
Import-PSSession $CSSession -AllowClobber
If ($Null -ne (Get-CsOnlineDirectoryTenant))
{
If (($host.ui.RawUI.WindowTitle) -notlike "*Connected To:*")
{
$host.ui.RawUI.WindowTitle += " - Connected To: Skype for Business"
}
Else
{
$host.ui.RawUI.WindowTitle += " - Skype for Business"
}
}
}
}
continue
}
Teams {
If ($null -eq (Get-Module @getModuleSplat -Name "MicrosoftTeams"))
{
Write-Error "MicrosoftTeams Module is not present!"
}
Else
{
Write-Verbose "Connecting to Teams"
If ($MFA -eq $True)
{
$TeamsConnect = Connect-MicrosoftTeams
If ($Null -ne ($TeamsConnect))
{
If (($host.ui.RawUI.WindowTitle) -notlike "*Connected To:*")
{
$host.ui.RawUI.WindowTitle += " - Connected To: Microsoft Teams"
}
Else
{
$host.ui.RawUI.WindowTitle += " - Microsoft Teams"
}
}
}
Else
{
$TeamsConnect = Connect-MicrosoftTeams -Credential $Credential
If ($Null -ne ($TeamsConnect))
{
If (($host.ui.RawUI.WindowTitle) -notlike "*Connected To:*")
{
$host.ui.RawUI.WindowTitle += " - Connected To: Microsoft Teams"
}
Else
{
$host.ui.RawUI.WindowTitle += " - Microsoft Teams"
}
}
}
}
continue
}
Default { }
}
}
}
#endregion

#region Customization by Jeffrey Veenhuis 14-10-2019
$exchange = $true
$msonline = $true
$security = $true
$azuread = $false
$skype = $false
$sharepoint = $false
$teams = $false

$optionschosen = $false

While(!$optionschosen){
Clear-Host
Write-Host "Which services do you want to connect to?
You will need the modules for each service you want to connect to.

[$(If ($exchange) {"X"} Else {" "})] 1. Exchange Online
[$(If ($msonline) {"X"} Else {" "})] 2. MSOnline (AzureAD v1)
[$(If ($security) {"X"} Else {" "})] 3. Security and Compliance Center
[$(If ($azuread) {"X"} Else {" "})] 4. AzureAD v2
[$(If ($skype) {"X"} Else {" "})] 5. Skype For Business
[$(If ($sharepoint) {"X"} Else {" "})] 6. Sharepoint
[$(If ($teams) {"X"} Else {" "})] 7. Teams
"

$key = Read-Host "Use any of the number keys to change which service you want to connect to, otherwise just press enter"

switch($key){
1 {$exchange = !$exchange; break}
2 {$msonline = !$msonline; break}
3 {$security = !$security; break}
4 {$azuread = !$azuread; break}
5 {$skype = !$skype; break}
6 {$sharepoint = !$sharepoint; break}
7 {$teams = !$teams; break}
default {$optionschosen = $true}
}
}

$services = @()

If ($exchange) {$services += "Exchange"}
If ($msonline) {$services += "MSOnline"}
If ($security) {$services += "SecurityAndCompliance"}
If ($azuread) {$services += "AzureAD"}
If ($skype) {$services += "SkypeForBusiness"}
If ($sharepoint) {$services += "Sharepoint"}
If ($teams) {$services += "Teams"}

Connect-Office365 -Service $services -MFA

It's slightly adjusted but it's something, and yes you'll have to login multiple times per module, got nothing around it.

Clock10 days