批量获取OneDrive文件夹中图片embed links的自动化方案咨询
Hey there! Let's tackle this problem of grabbing embed links for 5000 OneDrive images without the soul-crushing manual work. I've got two solid options for you—one that's no-code/low-code (perfect if you want to avoid coding entirely), and a detailed MS Graph walkthrough if you're willing to dip your toes into a bit of API work.
This is the easiest route if you don't have coding experience. Power Automate (Microsoft's workflow tool) can automate the entire process for you:
Step 1: Create a new cloud flow
Head to Power Automate and create a new "Instant cloud flow". Pick "Manually trigger a flow" as the trigger, then click "Create".Step 2: List all image files in your OneDrive folder
Add a new action: search for "List files in folder" (select either OneDrive or OneDrive for Business, depending on your account). Choose your target folder, and add this filter under "Filter Query" to only grab images:FileExtension eq '.jpg' or FileExtension eq '.png'(adjust extensions if you use other image types like.gif).Step 3: Loop through each file
Add an "Apply to each" action, and select the "value" output from the "List files in folder" step—this is your full list of images.Step 4: Generate the embed link for each file
Inside the loop, add the "Create share link" action. Select the current file from the loop, set "Link type" to "Embed", and choose your preferred "Link scope" (e.g., "Anonymous" for public access, "Organization" if only internal users need access).Step 5: Save links to a spreadsheet
Still inside the loop, add an "Add a row into a table" action (connect to an Excel file stored in OneDrive or Excel Online). Map the "Web URL" output from the "Create share link" step to a column like "Embed Link" in your table.Run the flow
Hit "Test" to start the process manually. It'll churn through all 5000 images and populate your spreadsheet with embed links. Note: Free Power Automate plans have run limits, so you might need to split this into batches if you hit a cap.
If you're open to a bit of code, MS Graph is the most scalable solution. Here's a step-by-step that even total newbies can follow:
1. Register an Azure AD App (to access MS Graph)
First, you need a "key" to authenticate API requests to your OneDrive:
- Go to the Azure Portal's App Registrations page and click "New registration".
- Name your app (e.g., "OneDrive Embed Link Tool"), select "Accounts in any organizational directory and personal Microsoft accounts" (or "Personal Microsoft accounts only" if that's all you need), set the redirect URI to
http://localhost, then click "Register". - Copy the Application (client) ID—you'll need this later.
- Go to "API permissions" > "Add a permission" > "Microsoft Graph" > "Delegated permissions". Search for and check
Files.Read.All, then click "Grant admin consent for [your account]" (since you're the admin for your personal account).
2. Get an Access Token
You need a token to authenticate your API requests. Use this simple Python script (no prior Python experience required—just copy-paste and fill in your details):
import requests # Replace with your client ID from step 1 CLIENT_ID = "YOUR_CLIENT_ID_HERE" REDIRECT_URI = "http://localhost" SCOPE = "https://graph.microsoft.com/Files.Read.All offline_access" # Step 1: Get authorization code auth_url = f"https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?client_id={CLIENT_ID}&response_type=code&redirect_uri={REDIRECT_URI}&scope={SCOPE}" print("Open this link in your browser, log in, and copy the 'code' parameter from the URL:") print(auth_url) auth_code = input("Paste the authorization code here: ") # Step 2: Exchange code for access token token_url = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token" payload = { "client_id": CLIENT_ID, "code": auth_code, "redirect_uri": REDIRECT_URI, "grant_type": "authorization_code", "scope": SCOPE } response = requests.post(token_url, data=payload) tokens = response.json() access_token = tokens["access_token"] # Save refresh token to reuse later without logging in again refresh_token = tokens.get("refresh_token")
3. Batch Fetch Embed Links
Now use the token to get all your image embed links and save them to a CSV:
import csv # First, get your target folder's ID # Replace "/Pictures/MyImageFolder" with your actual OneDrive folder path folder_path = "/Pictures/MyImageFolder" folder_response = requests.get( f"https://graph.microsoft.com/v1.0/me/drive/root:{folder_path}", headers={"Authorization": f"Bearer {access_token}"} ) folder_id = folder_response.json()["id"] # Fetch all image files (handle pagination since 5000 is more than default 200 per page) all_files = [] next_url = f"https://graph.microsoft.com/v1.0/me/drive/items/{folder_id}/children?$filter=file/mimeType eq 'image/jpeg' or file/mimeType eq 'image/png'" while next_url: response = requests.get(next_url, headers={"Authorization": f"Bearer {access_token}"}) data = response.json() all_files.extend(data.get("value", [])) next_url = data.get("@odata.nextLink") # Get embed links for each file and save to CSV with open("onedrive_embed_links.csv", "w", newline="", encoding="utf-8") as csvfile: writer = csv.writer(csvfile) writer.writerow(["File Name", "Embed Link"]) for file in all_files: # Create embed link via Graph API link_response = requests.post( f"https://graph.microsoft.com/v1.0/me/drive/items/{file['id']}/createLink", headers={"Authorization": f"Bearer {access_token}", "Content-Type": "application/json"}, json={"type": "embed", "scope": "anonymous"} ) embed_link = link_response.json()["link"]["webUrl"] writer.writerow([file["name"], embed_link]) print(f"Saved link for {file['name']}") print("All embed links saved to onedrive_embed_links.csv!")
Quick Notes for MS Graph:
- If your access token expires, use the refresh token to get a new one (add a quick request to the token endpoint with
grant_type=refresh_token). - Adjust the
scopein the createLink request if you don't want anonymous access (use "organization" or "users" instead).
内容的提问来源于stack exchange,提问作者Matthias

