0

Search Files Across Sites

by
Published today

Search every site and OneDrive the connected account can reach with Microsoft Search. `query` takes KQL (e.g. `budget filetype:xlsx`, `path:"https://contoso.sharepoint.com/sites/Finance"`). `entity_types` picks what to return: `driveItem` (files and folders), `listItem`, `list`, `site` or `drive`. Hits are under `value[0].hitsContainers[0].hits`; page with `from`. Work or school accounts only. Requires Sites.Read.All (covered by the default Sites.ReadWrite.All).

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
/**
6
 * Search Files Across Sites
7
 * Search every site and OneDrive the connected account can reach with Microsoft Search. `query` takes KQL (e.g. `budget filetype:xlsx`, `path:"https://contoso.sharepoint.com/sites/Finance"`). `entity_types` picks what to return: `driveItem` (files and folders), `listItem`, `list`, `site` or `drive`. Hits are under `value[0].hitsContainers[0].hits`; page with `from`. Work or school accounts only. Requires Sites.Read.All (covered by the default Sites.ReadWrite.All).
8
 */
9
export async function main(
10
  auth: RT.MsSharepoint,
11

12
  query: string,
13
  entity_types: ("driveItem" | "listItem" | "list" | "site" | "drive")[] = [
14
    "driveItem",
15
  ],
16
  fields: string[] | undefined,
17
  size: number = 25,
18
  from: number = 0
19
) {
20
  const request: { [key: string]: any } = {
21
    entityTypes: entity_types?.length ? entity_types : ["driveItem"],
22
    query: { queryString: query },
23
    from,
24
    size,
25
  }
26
  if (fields?.length) request.fields = fields
27

28
  const response = await fetch(`${graph}/search/query`, {
29
    method: "POST",
30
    headers: {
31
      Authorization: `Bearer ${auth.token}`,
32
      "Content-Type": "application/json",
33
      Accept: "application/json",
34
    },
35
    body: JSON.stringify({ requests: [request] }),
36
  })
37

38
  if (!response.ok) {
39
    throw new Error(`${response.status} ${await response.text()}`)
40
  }
41

42
  return await response.json()
43
}
44