Add Owner Group to Users OneDrive for Business

Every OneDrive for business site in SharePoint Online has a primary and secondry owner.  There are situations when primary owner leaves the company but during the initial setup administrator did not entered the secondry administrator value.  This value should be a group instead of a User.  Around a year ago I faced this situation with a customer who had over 40K OneDrive Sites created but now no one had ownership of these sites.  To add the site collection owner on these sites I used the script below.  This hopefuly will help someone else.

$Creds = Get-Credential -Message “Please enter SPO Admin Credentials.”
Start-Transcript -Path C:\temp\transcript.txt
Connect-MsolService -Credential $Creds

$SPOAdminSiteURL = “https://tenant-admin.sharepoint.com/”
#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path “C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll” -ErrorAction Stop
Add-Type -Path “C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll” -ErrorAction Stop
Add-Type -Path “C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.UserProfiles.dll” -ErrorAction Stop

Connect-SPOService -Url $SPOAdminSiteURL -Credential $Creds

$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Creds.UserName, $Creds.Password)
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SPOAdminSiteURL)
$ctx.Credentials = $credentials
$ctx.Load($ctx.Web);
$ctx.ExecuteQuery()

$NewSites =$null;
$NewSites = @();

$PeopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($ctx)
$PeopleLoader =[Microsoft.SharePoint.Client.UserProfiles.ProfileLoader]::GetProfileLoader($ctx)

#To Get the Group ID. Add the Group in People Picker in Site Collection Admin dialog on SPO Admin Center and then use the IE Developer Tools to click on it name
$CSVPath = “C:\Temp\UniUsers.csv”
$IAMCloudOneDriveID = “c:0-.f|rolemanager|s-1-5-21-3431014192-700181988-4181250490-129537758”
try
{
    $Data = Import-Csv -Path $CSVPath
   
    if($Data)
    {
        $Count = 0;
        foreach($User in $Data)
        {
            $Count++;
            try
            {
         
              $Start = (Get-Date).Second
              $Name = $($User.UserName).Trim();
              Write-Host “Getting Prifle Number $Count of $($Data.Count) for User $Name” -ForegroundColor Yellow
              $AccountName = “i:0#.f|membership|$Name”
              $UserProfile = $PeopleManager.GetPropertiesFor($AccountName)
              $ctx.Load($UserProfile)
              $ctx.ExecuteQuery()
             
              if($UserProfile.DisplayName -eq $null -and $UserProfile.Email -eq $null)
              {
                Write-Host “This user $Name does not exist in User Profile System…” -ForegroundColor Red
                continue
              }
            }
            catch
            {
              Write-Output “Error processing a profile “
            }
            $OneDriveUrl = $UserProfile.PersonalUrl
            if($OneDriveUrl.Contains(“Person”))
            {
              try
              {
                $PeopleManager.SetSingleValueProfileProperty($AccountName, “PersonalUrl”, “”);
                $ctx.ExecuteQuery();
                $OneDriveUrl = $null;
              }
              catch
              {
                $PeopleManager.SetSingleValueProfileProperty($AccountName, “PersonalSpace”, “”);
                $ctx.ExecuteQuery();
                $OneDriveUrl = $null;
              }
             
            }
           
            If ($OneDriveUrl -ne $null)
            {
                try
                {
               
                  $SiteUrl = “”
                  Write-Host “Starting to Add Group on User OneDrive for:” $AccountName -ForegroundColor Yellow
                  $SiteUrl = $UserProfile.PersonalUrl
                  Write-Host “”
                  $SiteUrl = $SiteUrl.Remove($SiteUrl.LastIndexOf(“/”),1)
                  $Site = Get-SPOSite -Identity $SiteUrl
                  if($Site)
                  {
                    Write-Host “Adding The Cloud Group …”-ForegroundColor Yellow
                    Set-SPOUser -Site $Site.Url -LoginName $IAMCloudOneDriveID -IsSiteCollectionAdmin $true -ErrorAction SilentlyContinue
                    Write-Host “Group Added Successfully in $($Site.Url)…” -ForegroundColor Green
                  }
                }
                catch
                {
                  Write-Output “Error processing a profile “
                }
             }
             else
             {
                Write-Host “Personal Url is null for $Name. So Creating personal Site…”
                $Email = $UserProfile.Email
                [string]$emails = $Email
                $PeopleLoader.CreatePersonalSiteEnqueueBulk($Email);
               
                Write-Host “Creating User Profile for $($Email)” -ForegroundColor Green
              
                $NewSite = New-Object PSObject
                Add-Member -input $NewSite noteproperty ‘AccountName’ $AccountName
                $NewSites += $NewSite
            }
            $End = (Get-Date).Second
            $Secs = $End – $Start
            $ExpectedTime = ($Data.Count – $Count) * $Secs
            Write-Host “Total Profiles $($Data.Count) Processed Profiles $Count” -ForegroundColor Cyan
            Write-Host “The script took $Secs second(s) to run.” -ForegroundColor DarkMagenta
            Write-Host “Expect this to complete in $(($ExpectedTime/60)) minutes or $(($ExpectedTime/60)/60) Hours” -ForegroundColor Red
           
        }
        foreach($object in $NewSites)
        {
            $AccountName = $object.AccountName
              $UserProfile = $PeopleManager.GetPropertiesFor($AccountName) 
              $ctx.Load($UserProfile)
              $ctx.ExecuteQuery()
             
              $SiteUrl = $UserProfile.PersonalUrl
              if($SiteUrl.Length -gt 0)
              {
                Write-Host “Personal Site Found for $AccountName …” -ForegroundColor Yellow
                $SiteUrl = $Url.Remove($Url.LastIndexOf(“/”),1)
                Set-SPOUser -Site $SiteUrl -LoginName $IAMCloudOneDriveID -IsSiteCollectionAdmin $true -ErrorAction SilentlyContinue
                Write-Host “Group Added Successfully in $($Site.Url)…” -ForegroundColor Green
                $continue = $false
              }
        }
    }
}
catch
{
    Write-Host “Failed.” -ForegroundColor Yellow
}
Stop-Transcript

Script is also available here

https://gallery.technet.microsoft.com/Add-Owner-Group-to-Users-06003db8

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s