Functions/Connect-SharePointOnlineAdminAccount.ps1
<#
.SYNOPSIS This function connects to SharePoint Online using admin account credentials or a MSPComplete Endpoint. .DESCRIPTION This function connects to SharePoint Online using admin account credentials or a MSPComplete Endpoint. It returns whether the connection and logon was successful. .EXAMPLE Connect-SharePointOnlineAdminAccount -Endpoint $Endpoint .EXAMPLE $Endpoint | Connect-SharePointOnlineAdminAccount .EXAMPLE Connect-SharePointOnlineAdminAccount -Username $username -Password $password -OrganizationName $organizationName #> function Connect-SharePointOnlineAdminAccount { [CmdletBinding(PositionalBinding=$false)] [OutputType([Bool])] param ( # The username of the SharePoint Online account. [Parameter(Mandatory=$true, ParameterSetName="credential")] [ValidateNotNullOrEmpty()] [String]$username, # The password of the SharePoint Online account. [Parameter(Mandatory=$true, ParameterSetName="credential")] [ValidateNotNull()] [SecureString]$password, # The name of the organization in Office 365. [Parameter(Mandatory=$true, ParameterSetName="credential")] [ValidateNotNullOrEmpty()] [String]$organizationName, # The MSPComplete Endpoint. [Parameter(Mandatory=$true, ParameterSetName="endpoint", ValueFromPipeline=$true)] [ValidateNotNull()] $endpoint ) # Check for existing connection if ($Global:SharePointOnlineConnectionEstablished) { Write-Warning "The connection to SharePoint Online has already been established." return $true } $Global:SharePointOnlineConnectionEstablished = $false # If given endpoint, retrieve credential directly if ($PSCmdlet.ParameterSetName -eq "endpoint") { $sharePointOnlineCredential = $endpoint | Get-CredentialFromMSPCompleteEndpoint $username = $sharePointOnlineCredential.Username if (!(Search-HashTable -HashTable $endpoint.ExtendedProperties -Key "OrganizationName")) { Write-Error "The endpoint does not have an 'OrganizationName' extended property." return $false } $organizationName = Search-HashTable -HashTable $endpoint.ExtendedProperties -Key "OrganizationName" } # Create the SharePoint Online credential from the given username and password else { $sharePointOnlineCredential = [PSCredential]::new($username, $password) } # Logon to SharePoint Online try { Connect-SPOService -Url "https://$($organizationName)-admin.sharepoint.com" -Credential $sharePointOnlineCredential -ErrorAction Stop # Logon was successful Write-Information "Connection and logon to SharePoint Online successful with username '$($username)'." $Global:SharePointOnlineConnectionEstablished = $true return $true } # Logon was unsuccessful catch { Write-Error "Failed SharePoint Online account login with username '$($username)'.`r`n$($_.Exception.Message)" return $false } } |