Add Site Collection Administrator for OneDrive for Business accounts on Office 365 in ER 2.0.25

Follow

This article applies to only ER 2.0.25.

To scan OneDrive for Business on Office 365, you must use a global administrator account that has been added as a Site Collection Administrator to all Target OneDrive for Business Site Collections.

Each OneDrive for Business account has a OneDrive for Business Site Collection that stores files for that account. By default, only the user that owns the OneDrive for Business account is set as a Site Collection Administrator for their account. Additional Site Collection Administrators have to be added explicitly by a Office 365 global administrator or the owner of the OneDrive for Business account.

Add Site Collection Administrator

Microsoft provides instructions on how to use the SharePoint Online Management Shell to add a secondary Site Collection Administrator to the Target OneDrive for Business accounts: https://support.office.com/en-gb/article/Assign-eDiscovery-permissions-to-OneDrive-for-Business-sites-422858ff-917b-46d4-9e5b-3397f60eee4d

We have provided a reference PowerShell script below that you can use to automate that process. Review this script before running it in your environment.

Note: Adding a Site Collection Administrator to OneDrive for Business accounts gives this administrator full access to the affected accounts.

Requirements:

Script: 

# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, 
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
# AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
# THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

## Add secondary administrator to all OneDrive for Business user profiles
# Uses the SharePoint Online Management Shell tools
# 1. Prompts user to enter:
#   a. Global administrator user principal name.
#   b. Tenant name.
#   c. Secondary administrator user principal name (to add to all OneDrive user profiles).
# 2. Attempts to connect using `Connect-SPOService -Url https://$TenantName-admin.sharepoint.com $credential`
# 3. Gets list of user profiles for tenant
# 4. Iterates over list to find OneDrive for Business accounts
# 5. Adds secondary admin UPN to user profiles with OneDrive for Business accounts

Write-Output "`Adding secondary administrator to all OneDrive for Business user profiles for tentant.`n"

#----
# Initializes log in same directory as script
$LogFilePath = "$pwd\AdminUpdate-$(get-date -uformat '%Y-%m-%d-%H_%M').csv"
if (!(Test-Path $LogFilePath)) {
  New-Item $LogFilePath -type file *>$null
  Write-Output "Created log file: $LogFilePath"
}
else {
  Write-Output "Logging to $LogFilePath"
}

#----
# Check if SharePoint Online Management Shell ps module is installed
if (!(Get-Command Get-SPOUser -ErrorAction SilentlyContinue)) {
  $err = "SharePoint Online Management Shell tools required."
  Write-Output $err
  $err | Out-File $LogFilePath -Append
  Exit 1
}

#----
# Initializes important variables
do {
  while (!($adminUPN)) {
    $adminUPN = Read-Host -Prompt "
Enter a global administrator account UPN (User Principal Name).
This is usually the full email address of an Office365 administrator account.
E.g. admin@contoso.onmicrosoft.com`n"}
  while (!($TenantName)) {
  $TenantName = Read-Host -Prompt "
Enter your Office365 tenant name/organisation name.
E.g. For @contoso.onmicrosoft.com, enter: contoso`n"}
  while (!($adminUPN_add)) {
    $adminUPN_add = Read-Host -Prompt "
Add global administrator UPN as a Site Collection
administrator to all OneDrive for Business user profiles. 
E.g. To add 'admin@contoso.onmicrosoft.com' to OneDrive user profiles, 
enter: admin@contoso.onmicrosoft.com`n"}
  Write-Output "`nGlobal Admin UPN: $adminUPN
Tenant name: $TenantName
Admin UPN to add: $adminUPN_add"
  #----
  # Retry block. If user confirms settings, sets $retryIndex to 1 and breaks do-until loop
  $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
    "Use these settings."
  $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
    "Change settings."
  $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
  $retry = $Host.UI.PromptForChoice("-------------------", "Use these settings?", $options, 0)
  switch ($retry) {
    0 { 
      $retryIndex = 1
      Write-Output "Global Admin UPN: $adminUPN
Tenant name: $TenantName
Admin UPN to add: $adminUPN_add" | Out-File $LogFilePath -Append
    }
    1 { 
      # reset values so basic validation can be done
      $adminUPN = $null
      $TenantName = $null
      $adminUPN_add = $null
      $retryIndex = 0 
    }
  }

} until ($retryIndex -eq 1)

#----
# Check if credentials pass; otherwise re-prompt user
do {
  $retryIndex=0
  try {
        $Credential = Get-Credential -UserName $adminUPN -Message "User Must be a Global Admin"
        Connect-SPOService -Credential $credential -Url https://$TenantName-admin.sharepoint.com
    # If successful, break loop
    # If err != nil, move into catch block
    $retryIndex++
  }
  catch {
    $err = $_.Exception
    Write-Output $err
    $err | Out-File $LogFilePath -Append

    #----
    # Retry block. If select yes (try again), restarts do-until loop to attempt Connect-SPOService again
    $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
      "Try connecting again."
    $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
      "Abort connection."
    $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
    $retry = $Host.UI.PromptForChoice("", "Try again?", $options, 0)
    switch ($retry) {
      0 { $retryIndex = 0 }
      1 { Exit 1 }
    }
  }
} until ($retryIndex -ne 0)

#----
# General try-catch to validate values obtained via SharePoint Online Management Tools
try {
  # Specify your organisation admin central url
  $AdminURI = "https://$TenantName-admin.sharepoint.com"
  $siteURI = "https://$TenantName-my.sharepoint.com"
  $loadInfo1 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
  $loadInfo2 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
  $loadInfo3 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.UserProfiles")
  $creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials ($Credential.UserName, $Credential.Password)
  # Add the path of the User Profile Service to the SPO admin URL, then create a new webservice proxy to access it
  $proxyaddr = "$AdminURI/_vti_bin/UserProfileService.asmx?wsdl"
  $UserProfileService = New-WebServiceProxy -Uri $proxyaddr -UseDefaultCredential False
  $UserProfileService.Credentials = $creds
  # Set variables for authentication cookies
  $strAuthCookie = $creds.GetAuthenticationCookie($AdminURI)
  $uri = New-Object System.Uri($AdminURI)
  $container = New-Object System.Net.CookieContainer
  $container.SetCookies($uri, $strAuthCookie)
  $UserProfileService.CookieContainer = $container
  # Sets the first User profile, at index -1
  $UserProfileResult = $UserProfileService.GetUserProfileByIndex(-1)
  Write-Output "Please wait. Getting list of OneDrive for Business user profiles..."

  # $UserProfileService calls will also include sharepoint online system profiles that are not 
  # part of userland i.e. not usable by sharepoint online admins or users.
  # There should be about 7 system profiles.
  # Don't panic if you can't get all of them
  $NumProfiles = $UserProfileService.GetUserProfileCount()

  # Initialize counters
  $i = 1
  $ExaminedProfiles=0
}
catch {
  # If any of the above fail, script will fail; therefore, exit gracefully.
  $err = $_.Exception
  Write-Output $err
  $err | Out-File $LogFilePath -Append
  Exit 1
}

# Final confirmation before script execution
do {
  $retryIndex=0
  $yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
    "Add $adminUPN_add to all OneDrive for Business user profiles."
  $no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
    "Cancel."
  $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
    $retry = $Host.UI.PromptForChoice("", "This will add $adminUPN_add to all OneDrive for Business user profiles. Are you sure?", $options, 0)
  switch ($retry) {
    0 { $retryIndex++; Continue }
    1 { Write-Output "Cancelling..."
      Exit 1 }
  }
} until ($retryIndex -ne 0)


#----
# Loop through all available User profiles
# As long as the next User profile is NOT the one we started with (at -1)...
While ($UserProfileResult.NextValue -ne -1) {
  Write-Output "Getting user $i" | Out-File $LogFilePath -Append
  # Look for the Personal Space object in the User Profile and retrieve it
  # (PersonalSpace is the name of the path to a user's OneDrive for Business site.
  # Users who have not yet created a OneDrive for Business site do not have this property set.)
  $Prop = $UserProfileResult.UserProfile | Where-Object { $_.Name -eq "PersonalSpace" }
  $Url = $Prop.Values[0].Value
  # If OneDrive is activated for the user (i.e. personal Site Collection or 
  # My Site site collection exists), then set the secondary admin
  if ($Url) {
    $sitename = $siteURI + $Url
    try {
      # If you change the $false to $true this will add a secondary user rather than remove it
      $temp1 = Set-SPOUser -Site $sitename -LoginName $adminUPN_add -IsSiteCollectionAdmin $true
      $status = "Updated secondary administrator for: $sitename"
      Write-Output $status 
      $status | Out-File $LogFilePath -Append
      $ExaminedProfiles++
    }
    catch [System.Exception] {
      $err = $Error[0].Exception
      Write-Output $err
      $err | Out-File $LogFilePath -Append
    }
  }
  # And now we check the next profile the same way...
  $UserProfileResult = $UserProfileService.GetUserProfileByIndex($UserProfileResult.NextValue)
  $i++
}

# Done
$Done = "Assigned global administrator as Site Collection to $ExaminedProfiles OneDrive for Business user profiles."
$Done | Out-File $LogFilePath -Append
Write-Output $Done
Exit 0
0 out of 0 found this helpful

Comments

0 comments

Please sign in to leave a comment.