We use cookies to improve your experience.
By your continued use of this site you accept such use.
For more details please see our privacy policy and cookies policy.

Script Repository

Export data from OneDrive

May 19, 2022 Views: 6837

The script exports data from a user OneDrive to a server folder. To run the script, you can use a custom command or scheduled task configured for the User object type.

For the script to work you will need to install a certificate for connection to SharePoint Online on the computer where Adaxes service runs. To do so:

  1. Create a certificate using the New-PnPAzureCertificate cmdlet.
  2. Assign the certificate to the Azure application whose credentials were used to register your Microsoft 365 tenant in Adaxes.
  3. Grant Azure application access to SharePoint (i.e. Sites.FullControl.All).
  4. Install the certificate on the computer where Adaxes service runs.

Parameters:

  • $certificateThumbprint - Specifies the Thumbprint of the certificate that will be used to connect to SharePoint Online. For information on how to retrieve the Thumbprint, see How to: Retrieve the Thumbprint of a Certificate.
  • $usernameMicrosoft365 - Specifies the LDAP name of the property that stores the value used to sign in to Microsoft 365 (Office 365).
  • $destinationFolderPath - Specifies the path to the folder to which OneDrive data will be exported.
  • $tenantName - Specifies the name of the Microsoft 365 tenant associated with the user. For information on how to check the tenant, see View Microsoft 365 tenant for a user.
  • $oneDriveSiteURL - Specifies the full URL of the OneDrive site.
Edit Remove
PowerShell
$certificateThumbprint = "9BCE7405DD63FD8DE7486FDD32D111667197BB8E" # TODO: modify me
$usernameMicrosoft365 = "%userPrincipalName%" # TODO: modify me
$destinationFolderPath = "\\Server\Share\%username%" # TODO: modify me
$tenantName = "MyTenant" # TOOD: modify me
$oneDriveSiteURL = "https://$tenantName-my.sharepoint.com/personal" # TODO: modify me

# Build OneDrive URL
$charsToReplace = @(".", "@")
$charsToReplace | %%{$usernameMicrosoft365 = $usernameMicrosoft365.Replace($_, "_")}
$oneDriveSiteURL = "$oneDriveSiteURL/$usernameMicrosoft365"

# Connecto to SharePoint Online
$tenant = $Context.CloudServices.GetO365Tenant()
$credential = $tenant.GetCredential()

try
{
    $connection = Connect-PnPOnline -Url $oneDriveSiteURL -ClientId $credential.AppId -Thumbprint $certificateThumbprint -Tenant "$tenantName`.onmicrosoft.com" -ReturnConnection
    
    # Get all items
    try
    {
        $items = Get-PnPListItem -List Documents -ErrorAction Stop
    }
    catch
    {
        $Context.LogMessage("An error occurred when retrieving OneDrive items. Error: " + $_.Exception.Message, "Error")
        return
    }
    
    if ($null -eq $items)
    {
        return # No items found
    }
    
    # Create directory structure
    $folders = $items | Where-Object {$_.FileSystemObjectType -eq "Folder"}
    $oneDrivePath = "/personal/$usernameMicrosoft365/Documents"
    foreach ($folder in $folders)
    {
        $folderPath = $folder.FieldValues.FileRef.Replace($oneDrivePath, "").Replace("/", "\")
        try
        {
            New-Item -Path "$destinationFolderPath$folderPath" -Force -ItemType "directory" -ErrorAction Stop
        }
        catch
        {
            $Context.LogMessage("An error occurred when creating the directory structure. Error: " + $_.Exception.Message, "Error")
            return
        }
    }
    
    # Download files
    $files = $items | Where-Object {$_.FileSystemObjectType -eq "File"}
    foreach ($file in $files)
    {
        $localFolderPath = $file.FieldValues.FileDirRef.Replace($oneDrivePath, "").Replace("/", "\")
        try
        {
            Get-PnPFile -Url $file.FieldValues.FileRef -Path "$destinationFolderPath$localFolderPath" -AsFile -Filename $file.FieldValues.FileLeafRef -ErrorAction Stop
        }
        catch
        {
            $Context.LogMessage("An error occurred when downloading the file $($file.FieldValues.FileRef). Error: " + $_.Exception.Message, "Warning")
            continue
        }
    }
}
finally
{
    # Close the connection and release resources
    if ($connection) { Disconnect-PnPOnline -Connection $connection }
}
Comments 18
avatar
DEREK AXE Sep 01, 2020
Keeps throwing a Null error at $tenant = $Context.BindToObjectByDN($tenantDN)
avatar
Support Sep 02, 2020

Hello Derek,

Do we understand correctly that you are executing the script in Windows PowerShell? The thing is that the script uses the built-in Adaxes variable $Context and thus can only be executed in a Business Rule, Custom Command or Scheduled Task. Also, please, make sure that the user for which the script is executed has an associated Microsoft 365 (former Office 365) tenant registered in Adaxes. For details, have a look at step 8 of the following tutorial:https://www.adaxes.com/tutorials_ActiveDirectoryManagement_ManageAndAutomateOffice365.htm#collapse1.

avatar
Craig Mohr Nov 13, 2020
You have a potential security risk in several places your script. You set permissions for the account and then do several checks that can fail out and return. If it fails you never remove those permissions. You should clean up those permissions before returning.
avatar
Support Nov 13, 2020
Thank you for pointing out the issue. We updated the script so it removes granted permissions in all cases.
avatar
Jeff Lamb Dec 10, 2020
Howdy

This script works great. Thank you.

I have been struggling to modify it to change the destination to a SharePoint site.
Would you happen to have anything available? (I cant see anything by conducting a search)

Thank you
Jeff
avatar
Support Dec 14, 2020
Hello Jeff,

Unfortunately, we do not have such examples. However, the following thread on Microsoft forums might be helpful:https://stackoverflow.com/questions/20237294/upload-file-to-sharepoint-document-library-using-powershell.
avatar
Remco Jan 27, 2021
Hi,

It works but the script will error out "The pipeline has been stopped." Is this due to the limitation of running a powershell script over approximately 9 minutes.

Thnx Remco
avatar
Support Jan 28, 2021
Hello Remco,

The error message means that the script execution exceeds the timeout configured in Adaxes. By default, the timeout is 10 minutes. As a solution, you can try running the script in a separate PowerShell process: https://www.adaxes.com/script-repository/run-script-in-new-powershell-instance-s290.htm.
avatar
Remco Tiel Feb 19, 2021
How can we use this script because we changed how adaxes connects to O365 from an account to app registration? $Context.GetOffice365Credential() is not valid anymore.

# Connecto to SharePoint Online
$microsoft365Credential = $Context.GetOffice365Credential()
Connect-SPOService -Url $url -Credential $microsoft365Credential

With regards,

Remco Tiel
avatar
Support Feb 19, 2021
Hello Remco,

We are working on updating the script accordingly. Unfortunately, we are not yet aware if it is possible to realize the behavior with the new modules. Once there are any updates we will get back to you right away.
avatar
Support Feb 19, 2021
Hello Remco,

Thank you for your patience. We updated the script and its description accordingly. Please, check it above. For information on how to use an Azure application to register your Microsoft 365 tenant in Adaxes, have a look at the following help article: https://www.adaxes.com/help/RegisterAdaxesAsAppMicrosoftAzure.
avatar
Brian F Apr 23, 2021
I used to use this script, but noticed at some point it stopped working. On "normal" usage OneDrive accounts, I can not get it to download files. I get the following error:

"An error occurred when retrieving OneDrive items. Error: The attempted operation is prohibited because it exceeds the list view threshold."
avatar
Support Apr 26, 2021
Hello Brian,

It looks like the error occurs when the accessed lists include more than 5000 files. For information on how to remedy the issue, please, have a look at the following Microsoft article: https://support.microsoft.com/en-us/office/manage-large-lists-and-libraries-b8588dae-9387-48c2-9248-c24122f07c59?ui=en-us&rs=en-us&ad=us#ID0EABAAA=Server.
avatar
Ed Feb 24, 2023
Hi,
This script looks great but having difficulties getting it to work. Getting errors
"An error occurred when retrieving OneDrive items. Error: The current connection holds no SharePoint context. Please use one of the Connect-PnPOnline commands which uses the -Url argument to connect." and " Parameter 'Connection' is obsolete. The -Connection parameter technically cannot function and therefore will be removed in a future version. Read the documentation of this cmdlet how to best deal with this: https://pnp.github.io/powershell/cmdlets/Disconnect-PnPOnline.html"
I tried adding the -Connection $connection to each PNP commandlet but whilst it no longer immediately errors it doesn't download anything stopped running after 14 minutes and gave the errors
"No connection to disconnect Stack trace: at <ScriptBlock>, <No file>: line 73
The pipeline has been stopped." Are you able to help?
Thanks
avatar
Support Feb 24, 2023
Hello Ed,

Unfortunately, we are not able to assist with this issue. It occurs in the cmdlet call itself which we have no access to. We recommend you to contact Microsoft support for assistance.
avatar
Ed Feb 24, 2023
OK, I have fixed this. I was doing the right thing by adding the Connection parameter to each command, I had infact made a typo on the file share so it wasn't writing the files. I think you should consider updating the script to include the above and remove the closing of the connection as that doesn't seem to work.
avatar
Carl Mar 14, 2023
thanks for the script. i have it mostly working.
When I try to copy the file, i have been getting

You cannot call a method on a null-valued expression.
At line:11 char:80
+ ... ccurred when downloading the file $($file.FieldValues.FileRef). Error ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
avatar
Support Mar 15, 2023
Hello Carl,

According to the error, you are executing the script incorrectly. As it is stated in the description, the script must be executed in a custom command or scheduled task configured for the User object type. It is not designed to run in Windows PowerShell.
Leave a comment
Loading...

Got questions?

Support Questions & Answers