azurepowershellsharepointmicrosoft-graph-apidrive

MSGraph Powershell New-MgDriveItemChild


I'm trying to use the Microsoft Graph Powershell module to create a a folder in a Sharepoint site's drive.

Looking at the documentation here I should be able to do the following:

Import-Module Microsoft.Graph.Files

$params = @{
    name = "New Folder"
    folder = @{
    }
    "@microsoft.graph.conflictBehavior" = "rename"
}

New-MgDriveItemChild -DriveId $driveId -DriveItemId $driveItemId -BodyParameter $params

However, this is giving me an error:

New-MgDriveItemChild_Create: You must provide either a file facet if creating a file or a folder facet if creating a folder or a remoteItem facet if adding a shared folder

Status: 400 (BadRequest)
ErrorCode: invalidRequest
Date: 2023-11-23T17:50:50

I have got the driveitem ID of the subfolder from the site's shared drive but it will not create the folder? I can use postman ok to create the folder directly via the API, but Powershell doesn't seem to like it.

Maybe my misunderstanding, but what is meant by a folder facet?


Solution

  • The error occurs if missed including folder facet while creating folder using Microsoft Graph PowerShell modules.

    When I ran your script to create new folder without defining folder facet, I too same error as below:

    Import-Module Microsoft.Graph.Files
    
    $params = @{
        name = "New Folder"
        folder = @{
        }
        "@microsoft.graph.conflictBehavior" = "rename"
    }
    
    $driveId = "xxxxxxx"
    $driveItemId = "xxxxxxxx"
    
    New-MgDriveItemChild -DriveId $driveId -DriveItemId $driveItemId -BodyParameter $params
    

    Response:

    enter image description here

    To resolve the error, you need to define at least one folder property like childCount or view or any property in the request body while creating folder with New-MgDriveItemChild cmdlet.

    When I ran below modified PowerShell script by including folder facet, I got response like this:

    Import-Module Microsoft.Graph.Files
    
    $params = @{
        name = "New Folder"
        folder = @{
            "childCount" = 1024
            "view" = @{
                "@odata.type" = "microsoft.graph.folderView"
            }
        }
        "@microsoft.graph.conflictBehavior" = "rename"
    }
    
    $driveId = "xxxxxxx"
    $driveItemId = "xxxxxxxx"
    
    New-MgDriveItemChild -DriveId $driveId -DriveItemId $driveItemId -BodyParameter $params
    

    Response:

    enter image description here

    To confirm that, I checked the same in OneDrive where new folder is created successfully as below:

    enter image description here

    Reference: Folder - Microsoft Graph v1.0