Microsoft Graph SDK PowerShell, uploading files, is there a way to define conflict behaviour e.g., fail if file already exists?

82 views Asked by At

I am using Microsoft Graph SDK for PowerShell (v2.9.0, also tried v2.15.0) to upload files to a drive (SharePoint Document Library). I use the following command to upload files.

Set-MgDriveItemContent -DriveId <String> -DriveItemId <String> [-Data <Stream>] -InFile <String> [-Break]
    [-HttpPipelineAppend <SendAsyncStep[]>] [-HttpPipelinePrepend <SendAsyncStep[]>] [-Proxy <Uri>] [-ProxyCredential
    <PSCredential>] [-ProxyUseDefaultCredentials] [-WhatIf] [-Confirm] [<CommonParameters>]

The command uses this endpoint

PUT    /drives/{drive-id}/items/{driveItem-id}/content

Question: Is there a way to use this parameter @microsoft.graph.conflictBehavior with the above command? I can use this parameter in Postman, with the above mentioned endpoint, to specify what happens if the file already exists in the SP document library. It could have one of the following values -> fail, replace, rename. However, so far, I haven't been able to find a way to this with Set-MgGraphDriveItemContent. Is there no way to do this?

The documentation https://learn.microsoft.com/en-us/graph/api/driveitem-put-content?view=graph-rest-1.0&tabs=powershell mentions the parameter 'BodyParameter' for this command, which may have been the solution for my problem. However, this parameter does not exist, at least not in the newer versions of Graph SDK for PowerShell >2.8.0.

Is there a way to specify this parameter @microsoft.graph.conflictBehavior with the command Set-MgDriveItemContent? or the only solution left for me is to make a separate GET call first to check if the file already exists or switch to creating upload session?

Any help on this would be highly appreciated.

1

There are 1 answers

1
RaytheonXie-MSFT On

You coould refer to following code

# Import required modules
Import-Module Microsoft.Graph.Authentication, Microsoft.Graph.Filesystems, Microsoft.Graph.Requests

# Define your authentication token
$accessToken = "YOUR_ACCESS_TOKEN"

# Initialize the GraphServiceClient
$client = New-GraphServiceClient -AccessToken $accessToken

# Define file path
$localFilePath = "C:\Path\to\Your\File.txt"

# Define target folder in OneDrive
$targetFolderId = "YOUR_TARGET_FOLDER_ID"

# Define conflict behavior (e.g., fail if file already exists)
$conflictBehavior = "fail"

# Upload file
Invoke-MgUploadContent -GraphClient $client -ConflictBehavior $conflictBehavior -Path $localFilePath -FolderId $targetFolderId