Use Microsoft Graph API to upload files to Sharepoint

I am trying to get autopilot 4k hardware hash info from each machine and manually upload to Intune, thus I use some online scripts and get them all together to make this PowerShell script to run from intune.

  1. Download Get-WindowsAutoPilotInfo.ps1
  2. Run the script and get the info
  3. Use App Registration to authenticate
  4. Upload to Sharepoint
 # Autopilot Hardware Hash Upload to Sharepoint
# Rui Qiu
# 2/27/2023
# v1.0

 # Getting hardware hash value
Invoke-WebRequest -Uri "" -OutFile "C:\Temp\autopilot.ps1"
$PC = hostname
CD C:\Temp\
PowerShell -NoProfile -ExecutionPolicy Unrestricted -Command .\autopilot.ps1 -OutputFile "C:\Temp\$PC.csv" -append 

# Getting variables for app registraion
# This app registration needs app permission for Sites.Read.All and Sites.ReadWrite.All

$clientId = "your app registration client id"  
$clientSecret = "the secret you created for that app registration"  
$tenantName = ""  
$resource = ""  

$tokenBody = @{

    Grant_Type    = 'client_credentials'  
    Scope         = ''  
    Client_Id     = $clientId  
    Client_Secret = $clientSecret

$tokenResponse = Invoke-RestMethod -Uri "$TenantName/oauth2/v2.0/token" -Method POST -Body $tokenBody -ErrorAction Stop

# This header is our authentication for API request
$headers = @{

    "Authorization" = "Bearer $($tokenResponse.access_token)"
    "Content-Type"  = "application/json"

# Find the object ID from Azure groups, the same name for your sharepoint site
$site_objectid = "object id of the sharepoint group from azure ad"
# The file you want to upload
$Filepath = "C:\temp\$pc.cvs"

$URL = "$site_objectid/sites/root"
$subsite_ID = (Invoke-RestMethod -Headers $headers -Uri $URL -Method Get).ID
$URL = "$subsite_ID/drives"
$Drives = Invoke-RestMethod -Headers $headers -Uri $URL -Method Get
$Document_drive_ID = ($Drives.value | where { $ -eq 'Documents' }).id
$Content = Get-Content -Path $Filepath
$Filename = (Get-Item -path $Filepath).Name
$puturl = "$Document_drive_ID/root:/Autopilot/$($Filename):/content"

$upload_headers = @{

    "Authorization" = "Bearer $($tokenResponse.access_token)"
    "Content-Type"  = "text/plain"

Invoke-RestMethod -Headers $upload_headers -Uri $puturl -Body $Content -Method PUT


Leave a Comment