Microsoft 365 OneDrive for Business: Delete File / Folder
This item deletes files and folders on OneDrive. It can delete multiple ones at once. It must contain one URL per line.
Configs: Common
  • Step Name
  • Note
Configs
  • C1: OAuth2 Setting *
  • C2: Data Item with File / Folder URLs to delete *

Notes

  • This Auto Step is for OneDrive for Business of Microsoft 365. It does not work for OneDrive personal.
  • To get the URL of a file/folder on OneDrive, open the Details window of the file/folder by clicking the Information icon, proceed to “More details”, and click the icon next to “Path”.
    How to get URL of file/folder

Capture

See also

Script (click to open)
  • An XML file that contains the code below is available to download
    • onedrive-file-delete.xml (C) Questetra, Inc. (MIT License)
    • If you are using Professional, you can modify the contents of this file and use it as your own add-on

// OAuth2 config sample at [OAuth 2.0 Setting]
// - Authorization Endpoint URL: https://login.microsoftonline.com/common/oauth2/v2.0/authorize
// - Token Endpoint URL: https://login.microsoftonline.com/common/oauth2/v2.0/token
// - Scope: https://graph.microsoft.com/Files.ReadWrite.All offline_access
// - Consumer Key: (Get by Microsoft Azure Active Directory)
// - Consumer Secret: (Get by Microsoft Azure Active Directory)

const GRAPH_URI = "https://graph.microsoft.com/v1.0/";

main();
function main(){
  //// == 工程コンフィグの参照 / Config Retrieving ==
  const oauth2 = configs.get("conf_OAuth2");
  const urlsDef = configs.getObject("conf_urls");

  //// == ワークフローデータの参照 / Data Retrieving ==
  const urlArray = retrieveUrlArray(urlsDef);

  //// == 演算 / Calculating ==
  checkHttpRequestingLimit(urlArray);
  deleteItems( urlArray, oauth2 );
}

/**
  * ワークフローデータから URL の配列を読み出す
  * @param {ProcessDataDefinitionView} urlsDef  データ項目の ProcessDataDefinitionView
  * @return {Array<String>} urlArray  URL の配列
  */
function retrieveUrlArray( urlsDef ) {
  const urls = engine.findData(urlsDef);
  if (urls === "" || urls === null) {
    throw "File / Folder URLs aren't set.";
  }
  let urlArray = urls.split("\n");
  urlArray = urlArray.filter(url => url !== ""); // 空文字列を削除
  if (urlArray.length === 0) {
    throw "File / Folder URLs aren't set.";
  }
  return urlArray;
}

/**
  * HTTPリクエストの上限を超えないか確認する
  * @param {Array<String>} urlArray  URL の配列
  */
function checkHttpRequestingLimit( urlArray ) {
  if ( urlArray.length * 2 > httpClient.getRequestingLimit() ){
    throw "Necessary HTTP requests exceeds the limit.";
  }
}

/**
  * ドライブアイテム(ファイル/フォルダ)を削除する。
  * @param {Array<String>} urlArray  ドライブアイテムの URL の配列
  * @param {String} oauth2  OAuth2 認証設定
  */
function deleteItems( urlArray, oauth2 ) {
  const itemNum = urlArray.length;
  for (let i = 0; i < itemNum; i++){
    const itemInfo = getItemInfoByUrl(urlArray[i],oauth2);
    deleteItem(itemInfo,oauth2,urlArray[i]);
  }
}

/**
  * ドライブアイテム(ファイル/フォルダ)の URL からアイテム情報(ドライブIDとアイテムID)を取得し、
  * オブジェクトで返す
  * @param {String} driveItemUrl  ドライブアイテムの URL
  * @param {String} oauth2  OAuth2 認証設定
  * @return {Object} itemInfo  ドライブアイテム情報 {driveId, id}
  */
function getItemInfoByUrl( driveItemUrl, oauth2 ) {
  // 分割代入
  const {
    id,
    parentReference: {
      driveId
    }
  } = getObjBySharingUrl( driveItemUrl, oauth2 ); // driveItemUrlが不正ならここでエラー
  const itemInfo = {driveId, id};
  return itemInfo;
}

/**
  * OneDriveのドライブアイテム(ファイル/フォルダ)のメタデータを取得し、JSONオブジェクトを返す
  * APIの仕様:https://docs.microsoft.com/ja-jp/onedrive/developer/rest-api/api/shares_get?view=odsp-graph-online
  * @param {String} sharingUrl  ファイルの共有URL
  * @param {String} oauth2  OAuth2 認証設定
  * @return {Object} responseObj  ドライブアイテムのメタデータのJSONオブジェクト
  */
function getObjBySharingUrl( sharingUrl, oauth2 ) {
  if (sharingUrl === "" || sharingUrl === null) {
    throw `Sharing URL is empty.`;
  }

  // encoding sharing URL
  const encodedSharingUrl = encodeSharingUrl(sharingUrl);

  // API Request
  const response = httpClient.begin() // HttpRequestWrapper
    .authSetting( oauth2 ) // Request HEADER (OAuth2 Token)
    .get( `${GRAPH_URI}shares/${encodedSharingUrl}/driveItem` ); // HttpResponseWrapper
  const httpStatus = response.getStatusCode();
  const responseStr = response.getResponseAsString();
  if (httpStatus >= 300) {
    const accessLog = `Deleting item: ${sharingUrl}\n---GET request--- ${httpStatus}\n${responseStr}\n`;
    engine.log(accessLog);
    throw `Failed to get drive item. status: ${httpStatus}`;
  }
  return JSON.parse( responseStr );
}

/**
  * 共有URLをunpadded base64url 形式にエンコードする
  * @param {String} sharingUrl  共有URL
  * @return {String} encodedSharingUrl  エンコードされた共有URL
  */
function encodeSharingUrl( sharingUrl ) {
  let encodedSharingUrl = base64.encodeToUrlSafeString( sharingUrl );
  while ( encodedSharingUrl.slice(-1) === '=' ) {
    encodedSharingUrl = encodedSharingUrl.slice(0,-1);
  }
  return `u!${encodedSharingUrl}`;
}

/**
  * ドライブアイテム(ファイル/フォルダ)を削除する。
  * @param {String,String} driveId,id  ドライブアイテムのドライブID、アイテムID
  * @param {String} oauth2  OAuth2 認証設定
  * @param {String} driveItemUrl  ドライブアイテムの URL
  */
function deleteItem( {
  driveId,
  id
}, oauth2, driveItemUrl){
  const apiUrl = `${GRAPH_URI}drives/${driveId}/items/${id}`;
  const response = httpClient.begin()
    .authSetting( oauth2 )
    .delete(apiUrl);

  const responseJson = response.getResponseAsString();
  const status = response.getStatusCode();
  if (status >= 300) {
    //when error thrown
    const accessLog = `Deleting item: ${driveItemUrl}\n---DELETE request--- ${status}\n${responseJson}\n`;
    engine.log(accessLog);
    throw `Failed to delete. status: ${status}`;
  }
}
  

1 thought on “Microsoft 365 OneDrive for Business: Delete File / Folder”

  1. Pingback: Utilising OneDrive from Your Workflow – Questetra Support

Comments are closed.

%d bloggers like this: