aasenomad
aasenomad

Reputation: 459

How to get Drive Item ID of a file from a user OneDrive using PowerShell Microsoft Graph

I'm trying to get a specific file's Drive Item ID from a user's OneDrive using Microsoft Graph. The sample script below is working, but it's really slow because it has to search the entire user's OneDrive.

Does anyone have any suggestions on how I can improve the speed, or know if there is another way to get a file's DriveItemID other than using Search-MgDrive command?

$DriveId = ""
$DriveItemID = (Search-MgDrive -DriveId $DriveId -Q "test.xlsx" | Where-Object { $_.Name -eq "test.xlsx" }).Id
Get-MgDriveItemVersion  -DriveId $DriveId -DriveItemId $DriveItemID

Upvotes: 0

Views: 462

Answers (1)

Sridevi
Sridevi

Reputation: 22202

Alternatively, you can make use of file path to get Drive Item ID instead of searching entire OneDrive.

I have one file named "test.xlsx" in Documents folder of user's OneDrive as below:

enter image description here

To get above file's Drive Item ID, you can refer below sample PowerShell script:

Connect-MgGraph -Scopes "Files.ReadWrite.All"

$UserId = "[email protected]"
$FilePath = "/Documents/test.xlsx"

$Drive = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/users/$UserId/drive"
$DriveId = $Drive.Id

$DriveItem = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/users/$UserId/drive/root:$FilePath"

$DriveItemID = $DriveItem.Id
Write-Host "The DriveItem ID is: $DriveItemID"

$DriveItemVersions = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/drives/$DriveId/items/$DriveItemID/versions"

$DriveItemVersions.value | ForEach-Object {
    Write-Host "Version ID: $($_.id), Last Modified: $($_.lastModifiedDateTime), Size: $($_.size) bytes"
}

Response:

enter image description here

Upvotes: 1

Related Questions