Home > Back-end >  Using Powershell to call the Graph Api to upload Folders and Files
Using Powershell to call the Graph Api to upload Folders and Files

Time:03-11

So I am writing this script that will allow me to upload folders and files to a SharePoint document library. In the moment I have one folder (TEST) on my local computer that contains a few other folders, which contain files. I am able to upload folders and files to SharePoint no problem, but I am having difficulty putting them in the correct File Structure. Below I am creating all the folders I need in the SharePoint site. I call the Graph API, and it creates all the folders at the root, but some of these folders don't belong at the root, but exist inside some of the other folders. I know I need to change the $CreateFolderURL, but I am unsure of how to keep track of which folder or file belongs inside of which folder. Basically I want the same local subdirectory structure replicated in the SharePoint Library

$Files = Get-ChildItem "C:\Users\Mark\Documents\TestUpload" -Recurse
write-host $Files

AllFolders($Files)
   
function AllFolders($Files){
    $CreateFolderURL = "https://graph.microsoft.com/v1.0/drives/(DriveID)/items/root/children"

    foreach($file in $Files){
         
         #check if folder or file
       if (! $file.PSIsContainer)
        {
        write-host "File"
        
        }
        else{
        
            
            $uploadFolderRequestBody = @{
            name= "$file"
            folder = @{}
            "@microsoft.graph.conflictBehavior"= "rename"
            } | ConvertTo-Json
   

    
            Invoke-RestMethod -Headers $header -Method Post -Body $uploadFolderRequestBody -ContentType "application/json" -Uri $CreateFolderURL


        }
        
    }
}

CodePudding user response:

This is not tested. The goal of this appears to be to create the subdirectory structure.

If you are on PowerShell 5.1 or higher, Get-ChildItem can specify a -Directory switch obviating the need to check PSIsContainer. The key is to replace the local base directory path with the URL path when setting $CreateFolderURL.

AllFolders('C:\Users\Mark\Documents\TestUpload')
   
function AllFolders($BaseDirectory) {
    $Directories = Get-ChildItem -Path $BaseDirectory -Recurse -Directory

    foreach ($Directory in $Directories) {
        $CreateFolderURL = 'http://graph.microsoft.com/v1.0/drives/(DriveID)/items/root/'  
            $_.FullName.Replace($BaseDirectory,'').Replace('\','/')
        $uploadFolderRequestBody = @{
            name= "$file"
            folder = @{}
            "@microsoft.graph.conflictBehavior"= "rename"
        } | ConvertTo-Json

        Invoke-RestMethod -Headers $header -Method Post -Body $uploadFolderRequestBody `
            -ContentType "application/json" -Uri $CreateFolderURL
    }
}
  • Related