0

Create Folder

by
Published today

Create a folder in your OneDrive, or in another drive when `drive_id` is set. `parent` is an id, or a path from the drive root starting with "/" (e.g. `/Reports/2026`), the root when empty. 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 4 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
/**
24
 * Create Folder
25
 * Create a folder in your OneDrive, or in another drive when `drive_id` is set. `parent` is an id, or a path from the drive root starting with "/" (e.g. `/Reports/2026`), the root when empty. Requires Files.ReadWrite (a connection default); a drive that is not your own needs Files.ReadWrite.All.
26
 */
27
export async function main(
28
  auth: RT.MsOnedrive,
29

30
  name: string,
31
  parent: string | undefined,
32
  conflict_behavior: "rename" | "replace" | "fail" = "rename",
33
  drive_id: string | undefined
34
) {
35
  const drive = driveUrl(drive_id)
36
  const response = await fetch(`${drive}/${ref(parent)}/children`, {
37
    method: "POST",
38
    headers: {
39
      Authorization: `Bearer ${auth.token}`,
40
      "Content-Type": "application/json",
41
      Accept: "application/json",
42
    },
43
    body: JSON.stringify({
44
      name,
45
      folder: {},
46
      "@microsoft.graph.conflictBehavior": conflict_behavior,
47
    }),
48
  })
49

50
  if (!response.ok) {
51
    throw new Error(`${response.status} ${await response.text()}`)
52
  }
53

54
  return await response.json()
55
}
56