0

Copy File or Folder

by
Published today

Copy a file or folder into another folder, optionally under a new name and into another drive (`destination_drive_id`). `item` and `destination_folder` are each an id, or a path from the drive root starting with "/" (e.g. `/Reports/2026/summary.xlsx`). Graph copies asynchronously: with `wait` the script polls for up to a minute, returns the final status with the new item's `resourceId` and fails if the copy failed (e.g. a name clash), otherwise it returns the `monitor_url` right away. Requires Files.ReadWrite (a connection default); a drive that is not your own needs Files.ReadWrite.All.

Script ms_onedrive Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 5 hours ago
1
//native
2

3
const graph = "https://graph.microsoft.com/v1.0"
4

5
function driveUrl(drive_id: string | undefined) {
6
  return drive_id != null && drive_id !== ""
7
    ? `${graph}/drives/${encodeURIComponent(drive_id)}`
8
    : `${graph}/me/drive`
9
}
10

11
// An item is addressed by its id, or by a path from the drive root starting with "/"
12
function ref(item: string | undefined) {
13
  if (item == null || item === "" || item === "/") return "root"
14
  if (!item.startsWith("/")) return `items/${encodeURIComponent(item)}`
15
  const path = item
16
    .replace(/\/+$/, "")
17
    .split("/")
18
    .map(encodeURIComponent)
19
    .join("/")
20
  return `root:${path}:`
21
}
22

23
async function folderId(
24
  token: string,
25
  drive: string,
26
  folder: string
27
): Promise<string> {
28
  if (!folder.startsWith("/")) return folder
29
  const response = await fetch(`${drive}/${ref(folder)}?$select=id`, {
30
    headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
31
  })
32
  if (!response.ok) {
33
    throw new Error(`${response.status} ${await response.text()}`)
34
  }
35
  return ((await response.json()) as { id: string }).id
36
}
37

38
/**
39
 * Copy File or Folder
40
 * Copy a file or folder into another folder, optionally under a new name and into another drive (`destination_drive_id`). `item` and `destination_folder` are each an id, or a path from the drive root starting with "/" (e.g. `/Reports/2026/summary.xlsx`). Graph copies asynchronously: with `wait` the script polls for up to a minute, returns the final status with the new item's `resourceId` and fails if the copy failed (e.g. a name clash), otherwise it returns the `monitor_url` right away. Requires Files.ReadWrite (a connection default); a drive that is not your own needs Files.ReadWrite.All.
41
 */
42
export async function main(
43
  auth: RT.MsOnedrive,
44

45
  item: string,
46
  destination_folder: string | undefined,
47
  new_name: string | undefined,
48
  destination_drive_id: string | undefined,
49
  wait: boolean = true,
50
  drive_id: string | undefined
51
) {
52
  const drive = driveUrl(drive_id)
53
  const body: { [key: string]: any } = {}
54
  if (new_name != null && new_name !== "") body.name = new_name
55
  const otherDrive = destination_drive_id != null && destination_drive_id !== ""
56
  if (otherDrive || (destination_folder != null && destination_folder !== "")) {
57
    const destinationDrive = otherDrive
58
      ? `${graph}/drives/${encodeURIComponent(destination_drive_id!)}`
59
      : drive
60
    body.parentReference = {
61
      id: await folderId(
62
        auth.token,
63
        destinationDrive,
64
        destination_folder || "/"
65
      ),
66
    }
67
    if (otherDrive) body.parentReference.driveId = destination_drive_id
68
  }
69

70
  const response = await fetch(`${drive}/${ref(item)}/copy`, {
71
    method: "POST",
72
    headers: {
73
      Authorization: `Bearer ${auth.token}`,
74
      "Content-Type": "application/json",
75
      Accept: "application/json",
76
    },
77
    body: JSON.stringify(body),
78
  })
79

80
  if (!response.ok) {
81
    throw new Error(`${response.status} ${await response.text()}`)
82
  }
83

84
  // 202 Accepted with an empty body; Location is a pre-authenticated monitor URL
85
  const monitor_url = response.headers.get("Location")
86
  if (!wait || !monitor_url) return { monitor_url }
87

88
  let status: { [key: string]: any } = {}
89
  for (let i = 0; i < 30; i++) {
90
    const poll = await fetch(monitor_url, { redirect: "manual" })
91
    // A finished copy may instead redirect to the new item
92
    if (poll.status >= 300 && poll.status < 400) {
93
      const resourceId = poll.headers
94
        .get("Location")
95
        ?.match(/\/items\/([^/?#:]+)/)?.[1]
96
      return { status: "completed", resourceId, monitor_url }
97
    }
98
    if (!poll.ok) throw new Error(`${poll.status} ${await poll.text()}`)
99
    status = await poll.json()
100
    if (status.status === "failed") throw new Error(JSON.stringify(status))
101
    if (status.status === "completed") break
102
    await new Promise((resolve) => setTimeout(resolve, 2000))
103
  }
104
  return { ...status, monitor_url }
105
}
106