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 Sites.ReadWrite.All (a connection default).

Script ms_sharepoint 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
export type DynSelect_site_id = string
6

7
export async function site_id(auth: RT.MsSharepoint) {
8
  const response = await fetch(
9
    `${graph}/sites?search=*&$select=id,displayName,webUrl&$top=200`,
10
    {
11
      headers: {
12
        Authorization: `Bearer ${auth.token}`,
13
        Accept: "application/json",
14
      },
15
    }
16
  )
17
  if (!response.ok) {
18
    throw new Error(`${response.status} ${await response.text()}`)
19
  }
20
  const { value } = (await response.json()) as {
21
    value: { id: string; displayName: string; webUrl: string }[]
22
  }
23
  return value.map((s) => ({
24
    value: s.id,
25
    label: `${s.displayName} (${s.webUrl})`,
26
  }))
27
}
28

29
export type DynSelect_drive_id = string
30

31
export async function drive_id(auth: RT.MsSharepoint, site_id: string) {
32
  const response = await fetch(
33
    `${graph}/sites/${site_id}/drives?$select=id,name`,
34
    {
35
      headers: {
36
        Authorization: `Bearer ${auth.token}`,
37
        Accept: "application/json",
38
      },
39
    }
40
  )
41
  if (!response.ok) {
42
    throw new Error(`${response.status} ${await response.text()}`)
43
  }
44
  const { value } = (await response.json()) as {
45
    value: { id: string; name: string }[]
46
  }
47
  return value.map((d) => ({ value: d.id, label: d.name }))
48
}
49

50
// The site's default document library, or the library given by drive_id
51
function driveUrl(site_id: string, drive_id: string | undefined) {
52
  return drive_id != null && drive_id !== ""
53
    ? `${graph}/drives/${encodeURIComponent(drive_id)}`
54
    : `${graph}/sites/${site_id}/drive`
55
}
56

57
// An item is addressed by its id, or by a path from the drive root starting with "/"
58
function ref(item: string | undefined) {
59
  if (item == null || item === "" || item === "/") return "root"
60
  if (!item.startsWith("/")) return `items/${encodeURIComponent(item)}`
61
  const path = item
62
    .replace(/\/+$/, "")
63
    .split("/")
64
    .map(encodeURIComponent)
65
    .join("/")
66
  return `root:${path}:`
67
}
68

69
async function folderId(
70
  token: string,
71
  drive: string,
72
  folder: string
73
): Promise<string> {
74
  if (!folder.startsWith("/")) return folder
75
  const response = await fetch(`${drive}/${ref(folder)}?$select=id`, {
76
    headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
77
  })
78
  if (!response.ok) {
79
    throw new Error(`${response.status} ${await response.text()}`)
80
  }
81
  return ((await response.json()) as { id: string }).id
82
}
83

84
/**
85
 * Copy File or Folder
86
 * 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 Sites.ReadWrite.All (a connection default).
87
 */
88
export async function main(
89
  auth: RT.MsSharepoint,
90
  site_id: DynSelect_site_id,
91
  item: string,
92
  destination_folder: string | undefined,
93
  new_name: string | undefined,
94
  destination_drive_id: string | undefined,
95
  wait: boolean = true,
96
  drive_id: DynSelect_drive_id | undefined
97
) {
98
  const drive = driveUrl(site_id, drive_id)
99
  const body: { [key: string]: any } = {}
100
  if (new_name != null && new_name !== "") body.name = new_name
101
  const otherDrive = destination_drive_id != null && destination_drive_id !== ""
102
  if (otherDrive || (destination_folder != null && destination_folder !== "")) {
103
    const destinationDrive = otherDrive
104
      ? `${graph}/drives/${encodeURIComponent(destination_drive_id!)}`
105
      : drive
106
    body.parentReference = {
107
      id: await folderId(
108
        auth.token,
109
        destinationDrive,
110
        destination_folder || "/"
111
      ),
112
    }
113
    if (otherDrive) body.parentReference.driveId = destination_drive_id
114
  }
115

116
  const response = await fetch(`${drive}/${ref(item)}/copy`, {
117
    method: "POST",
118
    headers: {
119
      Authorization: `Bearer ${auth.token}`,
120
      "Content-Type": "application/json",
121
      Accept: "application/json",
122
    },
123
    body: JSON.stringify(body),
124
  })
125

126
  if (!response.ok) {
127
    throw new Error(`${response.status} ${await response.text()}`)
128
  }
129

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

134
  let status: { [key: string]: any } = {}
135
  for (let i = 0; i < 30; i++) {
136
    const poll = await fetch(monitor_url, { redirect: "manual" })
137
    // A finished copy may instead redirect to the new item
138
    if (poll.status >= 300 && poll.status < 400) {
139
      const resourceId = poll.headers
140
        .get("Location")
141
        ?.match(/\/items\/([^/?#:]+)/)?.[1]
142
      return { status: "completed", resourceId, monitor_url }
143
    }
144
    if (!poll.ok) throw new Error(`${poll.status} ${await poll.text()}`)
145
    status = await poll.json()
146
    if (status.status === "failed") throw new Error(JSON.stringify(status))
147
    if (status.status === "completed") break
148
    await new Promise((resolve) => setTimeout(resolve, 2000))
149
  }
150
  return { ...status, monitor_url }
151
}
152