0

Get File or Folder

by
Published today

Get the metadata of a file or folder in your OneDrive, or in another drive when `drive_id` is set: name, size, web URL, parent, timestamps and a short-lived `@microsoft.graph.downloadUrl`. `item` is an id, or a path from the drive root starting with "/" (e.g. `/Reports/2026/summary.xlsx`). `expand` takes relationships such as `listItem`, `permissions` or `thumbnails`. Requires Files.Read (covered by the default Files.ReadWrite); a drive that is not your own needs Files.Read.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
/**
24
 * Get File or Folder
25
 * Get the metadata of a file or folder in your OneDrive, or in another drive when `drive_id` is set: name, size, web URL, parent, timestamps and a short-lived `@microsoft.graph.downloadUrl`. `item` is an id, or a path from the drive root starting with "/" (e.g. `/Reports/2026/summary.xlsx`). `expand` takes relationships such as `listItem`, `permissions` or `thumbnails`. Requires Files.Read (covered by the default Files.ReadWrite); a drive that is not your own needs Files.Read.All.
26
 */
27
export async function main(
28
  auth: RT.MsOnedrive,
29

30
  item: string,
31
  select: string | undefined,
32
  expand: string | undefined,
33
  drive_id: string | undefined
34
) {
35
  const drive = driveUrl(drive_id)
36
  const url = new URL(`${drive}/${ref(item)}`)
37
  if (select != null && select !== "") {
38
    url.searchParams.append("$select", select)
39
  }
40
  if (expand != null && expand !== "") {
41
    url.searchParams.append("$expand", expand)
42
  }
43

44
  const response = await fetch(url, {
45
    headers: {
46
      Authorization: `Bearer ${auth.token}`,
47
      Accept: "application/json",
48
    },
49
  })
50

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

55
  return await response.json()
56
}
57