OneDrive: Copy a File or Folder and Monitor Completion
See more OneDrive Examples
Creates a new item: copy a selected item to an explicitly addressed destination folder. A folder copy includes its descendants. The first run submits the request and saves its monitor URL; subsequent runs make one status request without submitting another copy. Use a fresh private receipt for each intentional operation and account. Schedule checks with backoff and honor Retry-After; 202 means accepted, not finished.
The receipt starts as pending before submission. A lost response or failed write requires reconciling the destination before starting again. Completed and failed receipts prevent automatic resubmission. Monitoring accepts JSON completion and 303 completion responses without automatically following redirects. A resourceId, when returned, is the new item ID and stays a string. Monitor URLs can expire; they are private, temporary operation state.
The default conflict behavior fails on a name collision. Copies inherit destination permissions and do not retain all source metadata. This example copies current content only. Copying all versions requires includeAllVersionHistory=true; Microsoft documents a current issue when it is combined with name, so copy first without name and rename afterward for that workflow. Folder copies are limited to 30,000 items; app-only cross-geo copy is unsupported.
Microsoft has announced changes to preauthenticated URLs beginning April 1, 2027. The example supports Graph-hosted URLs with the Graph token and an explicitly configured SharePoint host with a separate SharePoint-audience token. A legacy preauthenticated URL is requested without a bearer token. Never forward the Graph token to a SharePoint or content host. If required, prepare private qa_data/tokens/oneDrive-sharepoint.json with host and access_token from a separately authorized SharePoint token acquisition; token refresh must preserve that audience. A 401 requires checking the correct token audience or URL expiry, not blindly adding credentials.
Permission: Files.ReadWrite.
Uses direct Chilkat.Http requests to Microsoft Graph v1.0 in the global cloud. The delegated token is read from the private qa_data/tokens/oneDrive.json file created by the PKCE authorization example. Personal Microsoft accounts and Microsoft 365 work/school accounts can use delegated authorization when the app registration supports them. Refresh expired tokens; scopes and actual file access both matter.
For app-only Microsoft 365 access, use client credentials with administrator-approved application permissions. /me requires a signed-in user; app-only calls must address an authorized user, site, or drive explicitly. Client credentials do not grant access to personal OneDrive accounts. National clouds use their own authority and Graph hosts.
Check the expected HTTP status before using a response body. A false method result can still contain an HTTP error response; status zero means no response arrived. For 401, renew authorization; for 403, check permissions, access grants, and policy; for 429, honor Retry-After with a bounded retry. Reconcile uncertain writes before repeating them. Keep credentials, file contents, upload/download URLs, and detailed diagnostics private.
Chilkat PowerBuilder Downloads
integer li_rc
long li_Success
oleobject loo_Token
oleobject loo_Http
oleobject loo_Resp
oleobject loo_Result
string ls_DriveId
string ls_ItemId
oleobject loo_Endpoint
string ls_DestinationDriveId
string ls_DestinationFolderId
string ls_NewName
string ls_AccountKey
string ls_ReceiptPath
oleobject loo_Fac
oleobject loo_Receipt
oleobject loo_Body
string ls_MonitorUrl
string ls_StatusUrl
oleobject loo_ServiceUrl
oleobject loo_MonitorHttp
oleobject loo_ServiceHost
oleobject loo_TokenFiles
oleobject loo_SharepointToken
long li_Completed
li_Success = 0
// Assumes Chilkat is unlocked. See Global Unlock Sample.
li_Success = 0
// Obtain a delegated Graph token with this example's file permissions.
// See OneDrive OAuth2 with PKCE.
loo_Token = create oleobject
li_rc = loo_Token.ConnectToNewObject("Chilkat.JsonObject")
if li_rc < 0 then
destroy loo_Token
MessageBox("Error","Connecting to COM object failed")
return
end if
loo_Token.Strict = 1
li_Success = loo_Token.LoadFile("qa_data/tokens/oneDrive.json")
if li_Success <> 1 then
Write-Debug "Could not load the private OneDrive token cache."
destroy loo_Token
return
end if
if (loo_Token.JsonTypeOf("access_token") <> 1) OR (loo_Token.StringOfEquals("access_token","",1) = 1) then
Write-Debug "Expected a nonempty access_token in the JSON."
destroy loo_Token
return
end if
loo_Http = create oleobject
li_rc = loo_Http.ConnectToNewObject("Chilkat.Http")
loo_Http.AuthToken = loo_Token.StringOf("access_token")
loo_Http.RequireSslCertVerify = 1
loo_Http.FollowRedirects = 0
loo_Http.ConnectTimeout = 20
loo_Http.ReadTimeout = 120
loo_Http.SetRequestHeader("Accept","application/json")
loo_Resp = create oleobject
li_rc = loo_Resp.ConnectToNewObject("Chilkat.HttpResponse")
loo_Result = create oleobject
li_rc = loo_Result.ConnectToNewObject("Chilkat.JsonObject")
loo_Result.Strict = 1
ls_DriveId = "YOUR_DRIVE_ID"
ls_ItemId = "YOUR_ITEM_ID"
loo_Endpoint = create oleobject
li_rc = loo_Endpoint.ConnectToNewObject("Chilkat.StringBuilder")
loo_Endpoint.Append("https://graph.microsoft.com/v1.0/drives/")
loo_Endpoint.Append(loo_Http.UrlEncode(ls_DriveId))
loo_Endpoint.Append("/items/")
loo_Endpoint.Append(loo_Http.UrlEncode(ls_ItemId))
ls_DestinationDriveId = "YOUR_DESTINATION_DRIVE_ID"
ls_DestinationFolderId = "YOUR_DESTINATION_FOLDER_ID"
ls_NewName = "copied-file.txt"
// Use a separate private receipt for each copy operation and account.
ls_AccountKey = "YOUR_LOCAL_ACCOUNT_KEY"
ls_ReceiptPath = "qa_data/oneDrive/copy-receipt.json"
loo_Fac = create oleobject
li_rc = loo_Fac.ConnectToNewObject("Chilkat.FileAccess")
li_Success = loo_Fac.DirEnsureExists("qa_data/oneDrive")
if li_Success <> 1 then
Write-Debug "Could not create the private receipt directory."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
return
end if
loo_Receipt = create oleobject
li_rc = loo_Receipt.ConnectToNewObject("Chilkat.JsonObject")
loo_Receipt.Strict = 1
if loo_Fac.FileExists(ls_ReceiptPath) = 1 then
li_Success = loo_Receipt.LoadFile(ls_ReceiptPath)
if li_Success <> 1 then
Write-Debug "Invalid receipt; reconcile the existing operation before starting another."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
return
end if
if loo_Receipt.StringOfEquals("accountKey",ls_AccountKey,1) <> 1 then
Write-Debug "Receipt belongs to another copy operation; no request sent."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
return
end if
if loo_Receipt.StringOfEquals("sourceDriveId",ls_DriveId,1) <> 1 then
Write-Debug "Receipt belongs to another copy operation; no request sent."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
return
end if
if loo_Receipt.StringOfEquals("sourceItemId",ls_ItemId,1) <> 1 then
Write-Debug "Receipt belongs to another copy operation; no request sent."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
return
end if
if loo_Receipt.StringOfEquals("destinationDriveId",ls_DestinationDriveId,1) <> 1 then
Write-Debug "Receipt belongs to another copy operation; no request sent."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
return
end if
if loo_Receipt.StringOfEquals("destinationFolderId",ls_DestinationFolderId,1) <> 1 then
Write-Debug "Receipt belongs to another copy operation; no request sent."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
return
end if
if loo_Receipt.StringOfEquals("name",ls_NewName,1) <> 1 then
Write-Debug "Receipt belongs to another copy operation; no request sent."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
return
end if
if loo_Receipt.StringOfEquals("status","completed",1) = 1 then
Write-Debug "This copy already completed. Item ID: " + loo_Receipt.StringOf("resourceId")
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
return
end if
if loo_Receipt.StringOfEquals("status","failed",1) = 1 then
Write-Debug "The saved copy failed. Review its error and destination before starting another operation."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
return
end if
if loo_Receipt.StringOfEquals("status","monitoring",1) <> 1 then
Write-Debug "Copy outcome is uncertain; reconcile the destination before replacing this receipt."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
return
end if
if (loo_Receipt.JsonTypeOf("monitorUrl") <> 1) OR (loo_Receipt.StringOfEquals("monitorUrl","",1) = 1) then
Write-Debug "Expected a nonempty monitorUrl in the JSON."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
return
end if
else
loo_Receipt.UpdateString("accountKey",ls_AccountKey)
loo_Receipt.UpdateString("sourceDriveId",ls_DriveId)
loo_Receipt.UpdateString("sourceItemId",ls_ItemId)
loo_Receipt.UpdateString("destinationDriveId",ls_DestinationDriveId)
loo_Receipt.UpdateString("destinationFolderId",ls_DestinationFolderId)
loo_Receipt.UpdateString("name",ls_NewName)
// Save intent before POST so a lost response cannot cause an automatic duplicate copy.
loo_Receipt.UpdateString("status","pending")
li_Success = loo_Receipt.WriteFile(ls_ReceiptPath)
if li_Success <> 1 then
Write-Debug "Could not save the copy intent; nothing submitted."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
return
end if
loo_Body = create oleobject
li_rc = loo_Body.ConnectToNewObject("Chilkat.JsonObject")
loo_Body.UpdateString("parentReference.driveId",ls_DestinationDriveId)
loo_Body.UpdateString("parentReference.id",ls_DestinationFolderId)
loo_Body.UpdateString("name",ls_NewName)
loo_Endpoint.Append("/copy")
// Omit conflictBehavior: the default is fail, and the query option is not supported by personal OneDrive.
li_Success = loo_Http.HttpJson("POST",loo_Endpoint.GetAsString(),loo_Body,"application/json",loo_Resp)
if (li_Success <> 1) AND (loo_Resp.StatusCode = 0) then
Write-Debug "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
return
end if
if (loo_Resp.StatusCode <> 202) then
Write-Debug "Unexpected HTTP status: " + string(loo_Resp.StatusCode)
Write-Debug "Request ID: " + loo_Resp.GetHeaderField("request-id")
if loo_Resp.StatusCode = 429 then
Write-Debug "Retry-After: " + loo_Resp.GetHeaderField("Retry-After")
end if
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
return
end if
ls_MonitorUrl = loo_Resp.GetHeaderField("Location")
if ls_MonitorUrl = "" then
Write-Debug "Accepted without a monitor URL; keep the pending receipt and reconcile the destination."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
return
end if
loo_Receipt.UpdateString("monitorUrl",ls_MonitorUrl)
loo_Receipt.UpdateString("status","monitoring")
li_Success = loo_Receipt.WriteFile(ls_ReceiptPath)
if li_Success <> 1 then
Write-Debug "Accepted, but receipt save failed. Do not repeat POST; reconcile the destination."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
return
end if
Write-Debug "Copy accepted. Run again later to check its status; honor Retry-After."
Write-Debug "Retry-After: " + loo_Resp.GetHeaderField("Retry-After")
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
return
end if
// One status request per run. The caller schedules the next run with backoff and Retry-After.
ls_StatusUrl = loo_Receipt.StringOf("monitorUrl")
loo_ServiceUrl = create oleobject
li_rc = loo_ServiceUrl.ConnectToNewObject("Chilkat.Url")
li_Success = loo_ServiceUrl.ParseUrl(ls_StatusUrl)
if li_Success <> 1 then
Write-Debug "Invalid service URL."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
destroy loo_ServiceUrl
return
end if
if (loo_ServiceUrl.Ssl <> 1) OR (loo_ServiceUrl.Host = "") OR (loo_ServiceUrl.Login <> "") OR (loo_ServiceUrl.Password <> "") then
Write-Debug "Expected an HTTPS service URL without embedded login credentials."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
destroy loo_ServiceUrl
return
end if
loo_MonitorHttp = create oleobject
li_rc = loo_MonitorHttp.ConnectToNewObject("Chilkat.Http")
loo_MonitorHttp.RequireSslCertVerify = 1
loo_MonitorHttp.FollowRedirects = 0
loo_MonitorHttp.ConnectTimeout = 20
loo_MonitorHttp.ReadTimeout = 120
loo_ServiceHost = create oleobject
li_rc = loo_ServiceHost.ConnectToNewObject("Chilkat.StringBuilder")
loo_ServiceHost.Append(loo_ServiceUrl.Host)
if (loo_ServiceHost.ContentsEqual("graph.microsoft.com",0) = 1) AND (loo_ServiceUrl.Port = 443) then
loo_MonitorHttp.AuthToken = loo_Token.StringOf("access_token")
else
loo_TokenFiles = create oleobject
li_rc = loo_TokenFiles.ConnectToNewObject("Chilkat.FileAccess")
if loo_TokenFiles.FileExists("qa_data/tokens/oneDrive-sharepoint.json") = 1 then
loo_SharepointToken = create oleobject
li_rc = loo_SharepointToken.ConnectToNewObject("Chilkat.JsonObject")
loo_SharepointToken.Strict = 1
li_Success = loo_SharepointToken.LoadFile("qa_data/tokens/oneDrive-sharepoint.json")
if li_Success <> 1 then
Write-Debug "Could not read the private SharePoint token cache."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
destroy loo_ServiceUrl
destroy loo_MonitorHttp
destroy loo_ServiceHost
destroy loo_TokenFiles
destroy loo_SharepointToken
return
end if
if (loo_SharepointToken.JsonTypeOf("host") <> 1) OR (loo_SharepointToken.StringOfEquals("host","",1) = 1) then
Write-Debug "Expected a nonempty host in the JSON."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
destroy loo_ServiceUrl
destroy loo_MonitorHttp
destroy loo_ServiceHost
destroy loo_TokenFiles
destroy loo_SharepointToken
return
end if
if (loo_SharepointToken.JsonTypeOf("access_token") <> 1) OR (loo_SharepointToken.StringOfEquals("access_token","",1) = 1) then
Write-Debug "Expected a nonempty access_token in the JSON."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
destroy loo_ServiceUrl
destroy loo_MonitorHttp
destroy loo_ServiceHost
destroy loo_TokenFiles
destroy loo_SharepointToken
return
end if
// host is a configured exact hostname, not a URL and not obtained from the service response.
if (loo_ServiceHost.ContentsEqual(loo_SharepointToken.StringOf("host"),0) = 1) AND (loo_ServiceUrl.Port = 443) then
loo_MonitorHttp.AuthToken = loo_SharepointToken.StringOf("access_token")
end if
end if
end if
// With no matching token configured, only a still-valid preauthenticated URL can succeed.
li_Success = loo_MonitorHttp.HttpNoBody("GET",ls_StatusUrl,loo_Resp)
if (li_Success <> 1) AND (loo_Resp.StatusCode = 0) then
Write-Debug "No HTTP response received; inspect diagnostics privately and reconcile writes before retrying."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
destroy loo_ServiceUrl
destroy loo_MonitorHttp
destroy loo_ServiceHost
destroy loo_TokenFiles
destroy loo_SharepointToken
return
end if
if (loo_Resp.StatusCode <> 200) AND (loo_Resp.StatusCode <> 202) AND (loo_Resp.StatusCode <> 303) then
Write-Debug "Unexpected HTTP status: " + string(loo_Resp.StatusCode)
Write-Debug "Request ID: " + loo_Resp.GetHeaderField("request-id")
if loo_Resp.StatusCode = 429 then
Write-Debug "Retry-After: " + loo_Resp.GetHeaderField("Retry-After")
end if
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
destroy loo_ServiceUrl
destroy loo_MonitorHttp
destroy loo_ServiceHost
destroy loo_TokenFiles
destroy loo_SharepointToken
return
end if
li_Completed = loo_Resp.StatusCode = 303
if loo_Resp.BodyStr <> "" then
li_Success = loo_Result.Load(loo_Resp.BodyStr)
if li_Success <> 1 then
Write-Debug "Invalid monitor JSON; keep the receipt and inspect the operation."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
destroy loo_ServiceUrl
destroy loo_MonitorHttp
destroy loo_ServiceHost
destroy loo_TokenFiles
destroy loo_SharepointToken
return
end if
if loo_Result.StringOfEquals("status","completed",0) = 1 then
li_Completed = 1
end if
if loo_Result.StringOfEquals("status","failed",0) = 1 then
loo_Receipt.UpdateString("status","failed")
loo_Receipt.UpdateString("errorCode",loo_Result.StringOf("error.code"))
li_Success = loo_Receipt.WriteFile(ls_ReceiptPath)
if li_Success <> 1 then
Write-Debug "Could not save the failed-operation receipt."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
destroy loo_ServiceUrl
destroy loo_MonitorHttp
destroy loo_ServiceHost
destroy loo_TokenFiles
destroy loo_SharepointToken
return
end if
Write-Debug "Copy failed: " + loo_Result.StringOf("error.code")
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
destroy loo_ServiceUrl
destroy loo_MonitorHttp
destroy loo_ServiceHost
destroy loo_TokenFiles
destroy loo_SharepointToken
return
end if
end if
if li_Completed = 1 then
loo_Receipt.UpdateString("status","completed")
if loo_Result.JsonTypeOf("resourceId") = 1 then
loo_Receipt.UpdateString("resourceId",loo_Result.StringOf("resourceId"))
end if
li_Success = loo_Receipt.WriteFile(ls_ReceiptPath)
if li_Success <> 1 then
Write-Debug "Copy completed but the receipt could not be saved. Reconcile before another copy."
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
destroy loo_ServiceUrl
destroy loo_MonitorHttp
destroy loo_ServiceHost
destroy loo_TokenFiles
destroy loo_SharepointToken
return
end if
Write-Debug "Copy completed. Destination drive ID: " + ls_DestinationDriveId
Write-Debug "New item ID, if returned: " + loo_Receipt.StringOf("resourceId")
// A 303 without a JSON resourceId still indicates completion. Look up the destination by name if needed.
// Do not follow Location/resourceLocation with the Graph bearer token automatically.
else
Write-Debug "Copy not completed. Status: " + loo_Result.StringOf("status")
Write-Debug "Percent complete, if returned: " + loo_Result.StringOf("percentageComplete")
Write-Debug "Retry-After: " + loo_Resp.GetHeaderField("Retry-After")
end if
destroy loo_Token
destroy loo_Http
destroy loo_Resp
destroy loo_Result
destroy loo_Endpoint
destroy loo_Fac
destroy loo_Receipt
destroy loo_Body
destroy loo_ServiceUrl
destroy loo_MonitorHttp
destroy loo_ServiceHost
destroy loo_TokenFiles
destroy loo_SharepointToken