How to Sort OneDrive Photos and Videos by Year Using AI and PowerShell

Why I used AI for this job

I have 19 years of photos and videos stored in OneDrive, taking up almost 400 GB. Over time, pictures and videos had become mixed together in my Pictures folder.

When I tried moving the files through the OneDrive folder on my Windows desktop, my setup started downloading the online-only files first. I wanted to organise the collection without downloading it all to my computer.

My next idea was to use ChatGPT with the SharePoint connector. In my attempt, its folder-listing tool returned only up to 200 items per folder, and the available tool did not let me retrieve the remaining pages. This was a limit of that connector workflow, not a 200-file limit on OneDrive or SharePoint.

ChatGPT then suggested using PowerShell with Microsoft Graph to list the files and move them between folders inside OneDrive.

Why AI alone was not enough

AI helped me plan the job, write the scripts, check the file list, agree on date rules and understand errors. PowerShell performed the cloud requests after I signed in with Microsoft. Microsoft Graph provided access to the file metadata and folder moves. [1]

I still had to approve the plan and check the results. AI can produce incorrect code or choose the wrong year. It needs clear instructions, a read-only preview and a record of every move.

The sorting script should read names and metadata without requesting the photo or video contents. The script, Microsoft module and reports still use local storage. OneDrive sync or opening an online-only file may cause separate downloads. [2]

My goal

I wanted to separate the files in my mixed Pictures folder and sort them by year:

  • Pictures go under Pictures, for example Pictures/2024/Family/photo.jpg.
  • Videos go under Videos, for example Videos/2024/Family/video.mp4.
  • Useful album and event subfolders stay together.
  • Files with uncertain years go into _Year_Review under the correct media root.

I started with the mixed Pictures folder. Files that were already in Videos were left for a separate phase.

The main workflow had five steps. Installation errors, date fixes and interrupted runs are covered in troubleshooting at the end.

  1. Readiness check
  2. Create the file index
  3. Agree on date rules
  4. Build and preview the sorter
  5. Run and verify

Step 1 Readiness check

Before starting, make sure you have:

  • A Windows computer.
  • A stable internet connection.
  • The Microsoft account that owns the OneDrive files.
  • An AI assistant that can write and explain PowerShell scripts.

Keep one AI chat for the whole job. Tell it whether your Microsoft account is personal or work or school. Use your actual cloud folder names if they differ from Pictures and Videos.

Keep an independent backup of irreplaceable files. A move log helps with recovery, but it is not a backup.

Set up Microsoft Graph for OneDrive

The script needs the Microsoft Graph authentication module. Open a normal Windows PowerShell window, without Run as administrator. This command route uses Windows PowerShell 5.1. If you use PowerShell 7, ask the AI to adapt the commands. Microsoft recommends PowerShell 7 for Graph. [3]

Paste the following blocks one at a time. They create a job folder and download the module outside OneDrive:

$PSVersionTable.PSVersion
$jobRoot = Join-Path $env:LOCALAPPDATA 'OneDriveCloudSort\Job'
$moduleRoot = Join-Path $env:LOCALAPPDATA 'OneDriveCloudSort\Modules'
New-Item -ItemType Directory -Path $jobRoot,$moduleRoot -Force |
    Out-Null
[Net.ServicePointManager]::SecurityProtocol =
    [Net.SecurityProtocolType]::Tls12
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 `
    -Scope CurrentUser -Force
$saveOptions = @{
    Name = 'Microsoft.Graph.Authentication'
    Path = $moduleRoot
    Repository = 'PSGallery'
    ErrorAction = 'Stop'
}
Save-Module @saveOptions
$env:PSModulePath = $moduleRoot + ';' + $env:PSModulePath
Import-Module Microsoft.Graph.Authentication
Get-Module Microsoft.Graph.Authentication

The job folder holds scripts and reports, not your media files. Save-Module downloads the module to the chosen folder. Adding it to PSModulePath lets this window find it. [4] Read any repository prompt before accepting PSGallery.

Exit the OneDrive sync app

Wait for existing uploads to finish. Then use the OneDrive cloud icon in the Windows taskbar to quit the sync app. Keep it closed during the cloud job. You can still use OneDrive in a browser, and the script can connect through Graph.

Step 2 Create the file index

An index is a list of files. The AI uses it to check names, file types, sizes and folder paths without seeing the media contents.

Prompt to give the AI

Help me sort the mixed media in my OneDrive Pictures folder. Keep pictures under Pictures, move videos under Videos, and organise both by year. Preserve filenames and useful album folders. Do not delete, overwrite or remove duplicates.

First create Index-OneDrive-Cloud.ps1 for my account type and PowerShell version. Use Microsoft.Graph.Authentication and Microsoft Graph v1.0 with read-only access.

List Pictures and Videos recursively. Follow every @odata.nextLink page. Report any folder or page that cannot be read. Do not call an incomplete index complete.

Read metadata only. Never open local media or request contents, thumbnails or download URLs.

Save Index.csv and Index_Summary.txt beside the script using $PSScriptRoot. Include drive and item IDs, relative paths, names, extensions, MIME types, sizes, parent IDs, eTags and available dates. Leave missing fields blank. Summarise counts by root and file type, total bytes and errors. Do not include passwords or tokens.

Do not move anything yet. Give me the complete script and explain how to run it.

Save the script in the job folder. If downloading fails, open Notepad with the command below, paste the full script without code fence marks, and save as type All Files with UTF-8 encoding. The filename must end in .ps1, not .ps1.txt.

explorer $jobRoot
notepad (Join-Path $jobRoot 'Index-OneDrive-Cloud.ps1')
Test-Path (Join-Path $jobRoot 'Index-OneDrive-Cloud.ps1')

Test-Path must return True. Review the script before running it. After review, allow it in this PowerShell window and run the index:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
& (Join-Path $jobRoot 'Index-OneDrive-Cloud.ps1')

The execution policy change lasts only for this window and does not override organisation policy. Follow the Microsoft sign-in instructions and select the correct account. Do not share your password, token or live sign-in code with the AI. [5]

Upload Index.csv and Index_Summary.txt to the AI. Ask it to check the totals, file types and unread folders. A complete index must include every page of results. [6]

Step 3 Agree on date rules

A file’s created or modified date may be when it was copied or uploaded. It may not be when the photo or video was taken. Agree on the year rules before building the move plan.

  • Use a credible capture date if it is already available in cloud metadata.
  • Use a supported complete date in a filename, such as IMG_20240615, after checking that it is valid.
  • Use an existing year folder only if you confirm that it is reliable.
  • Put missing or conflicting years in _Year_Review. Do not guess.

For example, Pictures/2019/IMG_20220615.jpg has conflicting years. It needs review. A filename date is evidence, not proof of the capture date.

Prompt to give the AI

Analyse my index and propose year rules using only available metadata, complete filename dates and year folders I confirm as reliable. Do not use created or modified dates as capture dates by default.

Create Moves.csv with DriveId, FileId, Source, Destination, SizeBytes, ETag, MediaType, Year, DateSource, Reason and Action. Record files already correct and files intentionally left unchanged separately.

Keep useful album paths and avoid repeated year folders. Leave Lightroom catalogues, sidecar files and other supporting files unchanged unless I approve a separate plan.

Identify destination collisions. Never overwrite or delete files. Put uncertain years under Pictures/_Year_Review or Videos/_Year_Review, keeping the original relative path.

Account for every indexed file. Show totals and examples for each action, then wait for me to approve the plan.

Check examples from several years and file types. Resolve missing files, unknown extensions and name collisions. Save the approved plan beside the script.

Step 4 Build and preview the sorter

Ask the AI to build a script for your approved plan and account. Another person’s sorter may contain their drive ID or plan details. Do not reuse their move plan or progress log.

Prompt to give the AI

Create Sort-OneDrive-Cloud.ps1 for my account type, PowerShell version and approved Moves.csv. Use Microsoft.Graph.Authentication and Microsoft Graph v1.0.

Default mode must be a read-only preview. Only -Apply may move files or create destination folders. Save Cloud_Preview.csv beside the script. Check the account, approved drive, folder IDs and exact plan fingerprint before applying.

Use cloud moves inside the same drive. Never open local media, download media, upload, overwrite or delete files. Use stable item IDs, full pagination and conditional eTag requests. Skip changed files and occupied destinations for review.

Append an Intent before each move and Moved or Failed after it to Cloud_Move_Log.csv. Save progress to disk. Check each move’s ID, destination parent, name and size. On restart, reconcile the journal with current cloud metadata and skip verified completed moves.

Handle temporary timeouts and 429, 503 and 504 responses with bounded automatic retries. Respect Retry-After and use backoff. After an uncertain timeout, check the file’s current location before repeating a move. If retries are exhausted, save progress and stop clearly.

If batching is used, use at most 20 requests and check each response. Parse dates with explicit formats and invariant culture. Test English, Arabic Saudi and German settings.

Explain the code and permissions. Confirm that the commands below match the script’s parameters. Provide the full script and required plan files.

Ask the AI to review the code against these requirements and explain every cloud endpoint it calls. A capable person should review it if you cannot assess it yourself. An AI’s assurance is not proof that the code is correct.

Save the reviewed script and Moves.csv in the job folder. Run the preview:

Test-Path (Join-Path $jobRoot 'Sort-OneDrive-Cloud.ps1')
Test-Path (Join-Path $jobRoot 'Moves.csv')
& (Join-Path $jobRoot 'Sort-OneDrive-Cloud.ps1')

Both path checks must return True. The preview must not change cloud files. Upload Cloud_Preview.csv to the AI and compare it with the approved plan. Check Ready, AlreadyCompleted, Review, Skipped and Failed entries as applicable. Resolve unexpected results before applying.

You can ask for a small test group before the full run. Treat it as a check within this stage, rather than a separate main step.

Step 5 Run and verify

After checking and approving the preview, run:

& (Join-Path $jobRoot 'Sort-OneDrive-Cloud.ps1') -Apply

Keep the computer powered on, connected and awake. Keep OneDrive sync closed. Run only one copy of the job, even if you have more than one computer.

A large job can encounter temporary timeouts or throttling. With the retry logic requested above, the running script should wait and continue automatically. If the script stops or PowerShell closes, use the recovery instructions below. [7]

When the run finishes, upload the full move log and latest preview to the AI. Ask it to check the results against the approved plan:

Prompt to give the AI

Reconcile my approved plan and move log with current cloud metadata. Account for every file as moved, already correct, intentionally unchanged or unresolved. Count unique item IDs, not log rows.

Check planned moves by drive ID, item ID, destination parent, name and size. Resolve unfinished Intent entries and timeouts. Separate recorded success from independently verified success.

If you cannot access OneDrive directly, give me a read-only verification script and ask for its output. Do not claim live checks from logs alone.

Report completed, failed and remaining moves, plus files awaiting date review. Save a completion report and checkpoint. Do not claim the media contents or capture dates were audited unless they were checked.

Check a few destinations in OneDrive yourself. Files in _Year_Review still need a confirmed year. Handle them with a separate reviewed plan. Files originally in Videos can be the next phase, using a fresh index.

After verification, reopen OneDrive sync. Files set to stay on the device may download independently of the cloud sorter. Keep the original index, approved rules, script, plan, complete log and final report. [2]

Troubleshooting

Timeouts and automatic retries

Temporary timeouts and throttling can happen during a large job. The script must contain retry handling; asking AI for a sorter does not automatically provide it. While that script is running, let it wait and retry within its limit. If Microsoft provides a Retry-After delay, respect it. [7]

A timeout does not prove that a move failed. The file may already be at its destination. Before repeating an uncertain move, the script should check its current location by item ID. Each response in a batch must be checked separately. [8]

If you stop the job or change computers

Press Ctrl+C once and wait for the PowerShell prompt. Keep the whole job folder, including the plan, logs and state files. Automatic retry cannot restart a closed PowerShell window. You must start the script again.

On another computer, copy the job folder to the same job location, set up the module again and sign in with the same Microsoft account. Do not run the job on two computers at once.

In a fresh PowerShell window, restore the module path and run a read-only preview:

$jobRoot = Join-Path $env:LOCALAPPDATA 'OneDriveCloudSort\Job'
$moduleRoot = Join-Path $env:LOCALAPPDATA 'OneDriveCloudSort\Modules'
$env:PSModulePath = $moduleRoot + ';' + $env:PSModulePath
Import-Module Microsoft.Graph.Authentication
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
& (Join-Path $jobRoot 'Sort-OneDrive-Cloud.ps1')

Ask the AI to reconcile any unfinished Intent entries with current cloud metadata. Check the updated preview before running the command again with -Apply. The sorter should skip verified completed files and resume the remaining moves. If it does not support this behaviour, fix it before continuing.

The script does not exist

Use Test-Path to check the filename and folder. A command cannot run a file that was not saved. If downloading fails, ask for the full code and save it in Notepad as explained in Step 2.

Module installation fails in OneDrive Documents

Use the separate module folder in Step 1. Do not keep retrying an installation into a missing or redirected Documents folder. Add the module folder to PSModulePath in each new PowerShell window.

Microsoft sign in fails

Try a fresh normal PowerShell window and send the exact error to the AI. Check your account type. Work accounts may need administrator approval or an approved app registration. Do not bypass your organisation’s policy.

A date cannot be parsed

Stop before applying moves. Ask the AI to use explicit date formats and invariant culture, then test English, Arabic Saudi and German settings. Run the preview again after the fix.

A destination is occupied or a file starts downloading

Leave name collisions for review. A matching name or size does not prove that files are duplicates. If downloads start, check whether the script, OneDrive sync or a local preview app requested the contents before continuing.

The AI loses track of the job

Provide the saved rules, script, original index, approved plan, latest preview, full log and checkpoint. Ask it to check current cloud state before resuming. Keep these reports private because filenames and folder paths can contain personal information.

Microsoft reference links

Technical references checked on 1 November 2026. Interfaces, module versions and organisation policies can change. Verify current Microsoft instructions before a new job.

[1] Move a file inside a drive

[2] OneDrive Files On Demand

[3] Install Microsoft Graph PowerShell

[4] Save a PowerShell module

[5] Microsoft Graph sign in commands

[6] Read every page of Graph results

[7] Handle Graph throttling

[8] Combine Graph requests in a batch

Comments