Use Content Search to search the mailbox and OneDrive for Business site for a list of users

The Office 365 Security & Compliance Center provides a number of Windows PowerShell cmdlets that let you automate time-consuming eDiscovery-related tasks. Currently, creating a Content Search in the Security & Compliance Center to search a large number of custodian content locations takes time and preparation. Before you create a search, you have to collect the URL for each OneDrive for Business site and then add each mailbox and OneDrive for Business site to the search. In future releases, this will be easier to do in the Security & Compliance Center. Until then, you can use the script in this article to automate this process. This script prompts you for the name of your organization's MySite domain (for example, contoso in the URL https://contoso-my.sharepoint.com), a list of user email addresses, the name of the new Content Search, and the search query to use. The script gets the OneDrive for Business URL for each user in the list, and then it creates and starts a Content Search that searches the mailbox and OneDrive for Business site for each user in the list, using the search query that you provide.

Here are the steps to make this happen:

Step 1: Install the SharePoint Online Management Shell

Step 2: Generate a list of users

Step 3: Run the script to create and start the search

Before you begin

  • You have to be a member of the eDiscovery Manager role group in the Security & Compliance Center and a SharePoint Online global administrator to run the script in Step 3.

  • Be sure to save the list of users that you create in Step 2 and the script in Step 3 to the same folder. That will make it easier to run the script.

  • The script includes minimal error handling. It's primary purpose is to quickly and easily search the mailbox and OneDrive for Business site of each user.

  • The sample scripts provided in this topic aren’t supported under any Microsoft standard support program or service. The sample scripts are provided AS IS without warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages.

Step 1: Install the SharePoint Online Management Shell

The first step is to install the SharePoint Online Management Shell. You don't have to use the shell in this procedure, but you have to install it because it contains pre-requisites required by the script that you run in Step 3. These prerequisites allow the script to communicate with SharePoint Online to get the URLs for the OneDrive for Business sites.

Go to Set up the SharePoint Online Management Shell Windows PowerShell environment and perform Step 1 and Step 2 to install the SharePoint Online Management Shell.

Return to top

Step 2: Generate a list of users

The script in Step 3 will create a Content Search to search the mailboxes and OneDrive for Business sites of a list of users. You can just type the email addresses in a text file, or you can run a command in Windows PowerShell to get a list of email addresses and save them to a file (located in same folder that you'll save the script to in Step 3).

Here is a Windows PowerShell command (that you run by using remote PowerShell connected to your Exchange Online organization) to get a list of email addresses for all users in your organization and save it to a text file named Users.txt.

Get-Mailbox -ResultSize unlimited -Filter { RecipientTypeDetails -eq 'UserMailbox'} | Select-Object PrimarySmtpAddress > Users.txt

After you run this command, be sure to open the file and remove the header that contents the property name, PrimarySmtpAddress. The text file should just contain a list of email addresses, and nothing else. Make sure there are no blank rows before or after the list of users.

Return to top

Step 3: Run the script to create and start the search

When you run the script in this step, it will prompt you for the following information. Be sure to have this information ready before you run the script.

  • Your user credentials  The script will use your credentials to access SharePoint Online to get the OneDrive for Business URLs and to connect to the Security & Compliance Center with remote PowerShell.

  • Name of your MySite domain  The MySite domain is the domain that contains all the OneDrive for Business sites in your organization. For example, if the URL for your MySite domain is https://contoso-my.sharepoint.com, then you would enter contoso when the script prompts you for the name of your MySite domain.

  • Pathname of the text file from Step 2  The pathname of the text file that you created in Step 2. If the text file and the script are located in the same folder, then enter the name of the text file. Otherwise, enter the complete pathname for the text file. 

  • Name of the Content Search   The name of the Content Search that will be created by the script.

  • Search query   The search query that will be used with the Content Search is created and run. For more information about search queries, see Keyword queries and search conditions for Content Search.

  1. Save the following text to a Windows PowerShell script file by using a filename suffix of .ps1; for example, SearchEXOOD4B.ps1. Save the file to the same folder where you saved the list of users in Step 2.

    # This PowerShell script will prompt you for the following information:
    #    * Your user credentials 
    #    * The name of your organization's MySite domain                                              
    #    * The pathname for the text file that contains a list of user email addresses
    #    * The name of the Content Search that will be created
    #    * The search query string
    # The script will then:
    #    * Find the OneDrive for Business site for each user in the text file
    #    * Create and start a Content Search using the above information
    
    
    # Get user credentials
    if (!$credentials)
    {
        $credentials = Get-Credential
    }
    
    # Get the user's MySite domain name.  We use this to create the admin URL and root URL for OneDrive for Business
    $mySiteDomain = Read-Host "What is your organization's MySite domain?  For example,  'contoso' for 'https://contoso-my.sharepoint.com'"
    $AdminUrl = "https://$mySiteDomain-admin.sharepoint.com"
    $mySiteUrlRoot = "https://$mySiteDomain-my.sharepoint.com"
    
    # Get other required information
    $inputfile = read-host "Enter the file name of the text file that contains the email addresses for the users you want to search"
    $searchName = Read-Host "Enter the name for the new search"
    $searchQuery = Read-Host "Enter the search query you want to use"
    $emailAddresses = Get-Content $inputfile | where {$_ -ne ""}  | foreach{ $_.Trim() }
    
    # Connect to Office 365
    if (!$s -or !$a)
    {
        $s = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://ps.compliance.protection.outlook.com/powershell-liveid" -Credential $credentials -Authentication Basic -AllowRedirection -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
        $a = Import-PSSession $s -AllowClobber
    
        if (!$s)
        {
            Write-Error "Could not create PowerShell session."
            return;
        }
    }
    
    # Load the SharePoint assemblies from the SharePoint Online Management Shell
    # To install, go to http://go.microsoft.com/fwlink/p/?LinkId=255251
    if (!$SharePointClient -or !$SPRuntime -or !$SPUserProfile)
    {
        $SharePointClient = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
        $SPRuntime = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
        $SPUserProfile = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.UserProfiles")
    
        if (!$SharePointClient)
        {
            Write-Error "SharePoint Online Management Shell isn't installed, please install from: http://go.microsoft.com/fwlink/p/?LinkId=255251 and then run this script again"
            return;
        }
    }
    
    if (!$spCreds)
    {
        $spCreds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($credentials.UserName, $credentials.Password)
    }
    
    # Add the path of the User Profile Service to the SPO admin URL, then create a new webservice proxy to access it
    $proxyaddr = "$AdminUrl/_vti_bin/UserProfileService.asmx?wsdl"
    $UserProfileService= New-WebServiceProxy -Uri $proxyaddr -UseDefaultCredential False
    $UserProfileService.Credentials = $credentials
    
    # Take care of auth cookies
    $strAuthCookie = $spCreds.GetAuthenticationCookie($AdminUrl)
    $uri = New-Object System.Uri($AdminUrl)
    $container = New-Object System.Net.CookieContainer
    $container.SetCookies($uri, $strAuthCookie)
    $UserProfileService.CookieContainer = $container
    
    Write-Host "Getting each user's OneDrive for Business URL"
    $urls = @()
    foreach($emailAddress in $emailAddresses)
    {
        try
        {
            $prop = $UserProfileService.GetUserProfileByName("i:0#.f|membership|$emailAddress") | Where-Object { $_.Name -eq "PersonalSpace" } 
            $url = $prop.values[0].value
            $furl = $mySiteUrlRoot + $url
            $urls += $furl
            Write-Host "-$emailAddress => $furl"
        }
        catch
        {
            Write-Warning "Could not locate OneDrive for $emailAddress"
        }
    }
    
    Write-Host "Creating and starting the search"
    $search = New-ComplianceSearch -Name $searchName -ExchangeLocation $emailAddresses -SharePointLocation $urls -ContentMatchQuery $searchQuery
    
    # Finally, start the search and then display the status
    if($search)
    {
        Start-ComplianceSearch $search.Name
        Get-ComplianceSearch $search.Name
    }
    
  2. Open Windows PowerShell and go to the folder where you saved the script and the list of users from Step 2.

  3. Start the script; for example:

    .\SearchEXOOD4B.ps1
  4. When prompted for your credentials, enter your email address and password, and then click OK.

  5. Enter following information when prompted by the script. Type each piece of information and then press Enter.

    • The name of your MySite domain. 

    • The pathname of the text file that contains the list of users.

    • A name for the Content Search.

    • The search query (leave this blank to return all items in the content locations).

    The script gets the URLs for each OneDrive for Business site and then creates and starts the search. You can either run the Get-ComplianceSearch cmdlet to display the search statistics and results, or you can go to the Content search page in the Security & Compliance Center to view information about the search.

Return to top

Share Facebook Facebook Twitter Twitter Email Email

Was this information helpful?

Great! Any other feedback?

How can we improve it?

Thank you for your feedback!

×