Add AD Group to SharePoint Online Group using PowerShell

Requirement: Add AD Group to SharePoint Online Group using PowerShell

PowerShell to Add Active Directory Group to SharePoint Online Group
#Load SharePoint Online Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

Function Add-ADGroupToSP($SiteURL,$ADGroupName,$SPGroupName)
{
    #Setup Credentials to connect
    $Cred = Get-Credential
    $Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
 
    Try {
        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Cred
     
        #Get the Web and SharePoint Group
        $Web = $Ctx.Web
        $Group= $Web.SiteGroups.GetByName($SPGroupName)
 
        #Resolve the AD Security Group
        $ADGroup = $web.EnsureUser($ADGroupName)
 
        #Add Member to SharePoint group
        $Result = $Group.Users.AddUser($ADGroup)
        $Ctx.Load($Result)
        $Ctx.ExecuteQuery()
 
        write-host  -f Green "Active Directory Group '$ADGroupName' has been added to '$SPGroupName'"
    }
    Catch {
        write-host -f Red "Error:" $_.Exception.Message
    }
}

#Variables for Processing
$SiteURL = "https://crescenttech.sharepoint.com/Sales"
$ADGroupName = "Marketing Managers"
$SPGroupName="Sales Portal Members"

#Call the function to add AD group to SharePoint Group
Add-ADGroupToSP -SiteURL $SiteURL -ADGroupName $ADGroupName -SPGroupName $SPGroupName
Add AD Group to SharePoint Online Group using PowerShell Add AD Group to SharePoint Online Group using PowerShell Reviewed by Salaudeen Rajack on April 08, 2018 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.