Friday, March 11, 2016

PowerShell to add global Security Group to all site collections on SharePoint Online

Here is PowerShell script to add a global Security Group to all existing site collections on SharePoint Online

Need to run this script from SharePoint Online Management Shell

1. Create a new Security Group from your O365 Admin Center

Navigate to Groups



Click on Add Group button



In Add New Group popup, select Security Group for Type, provide Name, select Private for Privacy , provide Owner for the group and click Add

2. Add Members to the group. After adding the Group, select your Group and a popup appears to Add Members. Add the Members and close the popup

3. Get Account ID for the Group using SharePoint Online Management Shell

Run the below script to get the Account ID of the Group. This is required to add the group to you SharePoint Online sites

$User = '<globaladmin>@yourtenant.onmicrosoft.com'
$Pass = ConvertTo-SecureString 'globaladminpassword' -AsPlainText -Force
Connect-MsolService  -Credential $cred -ErrorAction Stop
Get-MsolGroup -All | Where-Object {$_.DisplayName -eq ‘Yourgroupname’}

This will return your Group details. Copy Account ID for Group (Account ID will be in the format of "c:0-.f|rolemanager|<long code similar to GUID>

4. Run the below script after replacing all required details with your tenant specific details to add your Security Group to all existing Site Collections in the tenant with Full Control or as Site Collection Administrator.

$User = '<globaladmin>@yourtenant.onmicrosoft.com'
$Pass = ConvertTo-SecureString 'globaladminpassword' -AsPlainText -Force
$adminURL = "https://yourtenant-admin.sharepoint.com"
$cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $User, $Pass

Connect-SPOService -Url $adminURL -Credential $cred

$sites = Get-SPOSite #Gets all the Site Collections

foreach($site in $sites){
    try{
        New-SPOSiteGroup -Site $site.Url -Group "Your SP Group Name" -PermissionLevels "Full Control" #Creates new SP group in the site with Full Control permissions
        Add-SPOUser -Site $site.Url -LoginName "<yourglobalgroupuserid>" -Group "Your SP Group Name" #Adds your Security Group to the SP group
        Set-SPOUser -Site $site.Url -LoginName "c:0-.f|rolemanager|<yourglobalgroupuserid>" -IsSiteCollectionAdmin $true

       # write-host "Success for " $site.Url
    }
    catch{
        #write-host "Failed for site " $site.Url
    }
}

Disconnect-SPOService