Microsoft 365 OneDrive for Business: Move File / Folder

Microsoft 365 OneDrive for Business: Move File / Folder

Microsoft 365 OneDrive for Business: ファイル / フォルダ移動

This item moves the specified file/folder to the specified folder on OneDrive. The file/folder cannot be moved between drives.

Basic Configs
Step Name
Note
Auto Step icon
Configs for this Auto Step
conf_OAuth2
C1: OAuth2 Setting *
conf_SourceUrl
C2: File / Folder URL to move *
conf_DestUrl
C3: Folder URL to move to *
conf_NewUrl
C4: Data item to save new file / folder URL after being moved

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”

Capture

See Also

Script (click to open)
  • An XML file that contains the code below is available to download
    • onedrive-file-move.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 auto step

// OAuth2 config sample at [OAuth 2.0 Setting]
// - Authorization Endpoint URL: https://login.microsoftonline.com/{your-tenant-id}/oauth2/v2.0/authorize
// - Token Endpoint URL: https://login.microsoftonline.com/{your-tenant-id}/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/";

function main() {
    //// == Config Retrieving / 工程コンフィグの参照 ==
    const oauth2 = configs.getObject('conf_OAuth2');
    const sourceUrl = retrieveSourceUrl();
    const destUrl = retrieveDestUrl();
    const newUrlDef = configs.getObject('conf_NewUrl');

    //// == Calculating / 演算 ==
    // getting itemInfo for Requesting Copy and Updating Data
    const sourceInfo = getItemInfoByUrl(oauth2, sourceUrl);
    const destInfo = getItemInfoByUrl(oauth2, destUrl);
    // sending Move Request
    const newUrl = moveDriveItem(oauth2, sourceInfo, destInfo);

    //// == ワークフローデータへの代入 / Data Updating ==
    if (newUrlDef !== null) {
        engine.setData(newUrlDef, newUrl);
    }
}

/**
  * config から移動するアイテムの URL を読み出す
  * 文字型データ項目のみ
  * 空の場合はエラー
  * @return {String} sourceUrl
  */
function retrieveSourceUrl() {
    const sourceUrl = engine.findData(configs.getObject('conf_SourceUrl'));
    if (sourceUrl === null) {
        throw 'Source file / folder URL is blank.';
    }
    return sourceUrl;
}

/**
  * config から移動先フォルダの URL を読み出す
  * 文字型データ項目、または固定値
  * 空の場合はエラー
  * @return {String} destUrl
  */
function retrieveDestUrl() {
    const destUrlDef = configs.getObject('conf_DestUrl');
    let destUrl = configs.get('conf_DestUrl');
    if (destUrlDef !== null) {
        destUrl = engine.findData(destUrlDef);
    }
    if (destUrl === '' || destUrl === null) {
        throw 'Destination folder URL is blank.';
    }
    return destUrl;
}

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

/**
  * OneDrive のドライブアイテム(ファイル、フォルダ)のメタデータを取得し、JSON オブジェクトを返す
  * APIの仕様: https://docs.microsoft.com/ja-jp/onedrive/developer/rest-api/api/shares_get?view=odsp-graph-online
  * @param {String} oauth2  OAuth2 認証設定
  * @param {String} sharingUrl  ドライブアイテムの共有URL
  * @return {Object} responseObj  ドライブアイテムのメタデータのJSONオブジェクト
  */
function getObjBySharingUrl(oauth2, sharingUrl) {
    const encodedSharingUrl = encodeSharingUrl(sharingUrl);
    const response = httpClient.begin()
        .authSetting(oauth2)
        .queryParam('select', 'id,parentReference/driveId')
        .get(`${GRAPH_URI}shares/${encodedSharingUrl}/driveItem`);
    const status = response.getStatusCode();
    const responseStr = response.getResponseAsString();
    if (status !== 200) {
        engine.log(responseStr);
        throw `Failed to get drive item. status: ${status}`;
    }
    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 {AuthSettingWrapper} oauth2  OAuth2 認証設定
  * @param {Object} sourceInfo  移動するアイテム情報 {driveId, id}
  * @param {Object} destInfo  移動先フォルダ情報 {driveId, id}
  * @return {String} newUrl  移動したアイテムの新しい URL
  */
function moveDriveItem(oauth2, sourceInfo, destInfo) {
    if (sourceInfo.driveId !== destInfo.driveId) {
        throw 'Cannot move between drives. Copy the file/folder instead.';
    }
    const apiUri = `${GRAPH_URI}drives/${sourceInfo.driveId}/items/${sourceInfo.id}`;
    const requestBodyObj = {
        parentReference: {
            id: destInfo.id
        }
    };
    const response = httpClient.begin()
        .authSetting(oauth2)
        .body(JSON.stringify(requestBodyObj), 'application/json')
        .patch(apiUri);
    const status = response.getStatusCode();
    const responseStr = response.getResponseAsString();
    if (status !== 200) {
        engine.log(responseStr);
        throw `Failed to move. status: ${status}`;
    }
    return JSON.parse(responseStr).webUrl;
}

    
Scroll to Top

Discover more from Questetra Support

Subscribe now to keep reading and get access to the full archive.

Continue reading