Skip to main content

Download & read files via PowerShell

 

<#region PREP
# DIE FOLGENDEN BEIDEN STEPS SIND NUR VORBEREITUNG UND MÜSSEN NICHT JEDES MAL DURCHGEFÜHRT WERDEN.



# STEP 1:Requirements: App RegRegistration erstellenwith mitappropriate denpermissions, folgendenas Permissionsdescribed Delegatedhere: - User.Read DelegatedSharePoint -files Files.Read.Selected... Delegated| -LNC Sites.Read.AllDOCS Application(lucanoahcaprez.ch)

-

With Sites.Selectedthis #tutorial, STEPfiles 2:can Appbe aufread from SharePoint Online repositories automatically and without user interaction. This can be especially valuable when large accesses to files need to be made, but the budget for Azure Blob Storage, for example, is not available. It also allows very easy customization of the corresponding files in SharePoint Online, which can then be used directly in the automation.

Preparations

First of all, the app registration must be created with the appropriate permissions. This is described here: Read SharePoint files ... | LNC DOCS (lucanoahcaprez.ch) Then the app must be assigned the appropriate permissions on SharePoint Online once.

This can be achieved with the following PowerShell code. The two upper variables must be filled in accordingly with the SharePoint Site berechtigenURL and the App Registration ID.

$siteUrl = "https://<yourtenantname>.sharepoint.com/sites/<yoursitename>/_api/site/id"
$ClientId = "<yourappid>"

# URLConnect derto Seite, worauf der Zugriff vergeben werden soll
$appId = "" # ID der App mit Sites.Selected Permission

# Verbinden auf SPSPO Site (PNPOnline Modul benötigt)required)
Connect-PnPOnline -Url $siteUrl -Interactive #

Anmeldung als Site Owner

# DerGrant write permission to the App dieRegistration Schreibberechtigungto aufthe dercorresponding SPSPO Sitesite und& allen Files darauf vergebenfiles
Grant-PnPAzureADAppSitePermission -Permissions "Write" -Site $siteUrl -AppId $appIdClientId -DisplayName "$AppIDClientId - Write Access"
#endregion

Getting PREP#>the #files DIEvia SITEGraph IDAPI

KANN

The ÜBERfollowing DENcode FOLGENDENcan URLbe ABGEHOLTused WERDEN:in https://bkwfmbenergie.sharepoint.com/sites/T_BKH_MWP3_Files/_api/site/idan automation for example. Here all files are written into an array without the execution needing any interaction.
It is also important here that the variables are correctly filled in at the beginning.

$SiteID = "f57476be-a118-4369-ba26-e7c1aac95847"<yoursharepointsiteid>"
#$TenantId NAME= DER"<yourtenantid>"
BIBLIOTHEK,$ClientId IN= DER"<yourappregistrationid>"
SICH$ClientSecret DIE= DATEIEN BEFINDEN"<yourclientsecret>"
$LibraryName = "Dokumente"


# DOWNLOAD VARIABLESDocuments"
$OutPathRoot = "C:\Users\RUTRA\OneDrive - BKW\Desktop\GraphDownload"<youroutputfolderforfilecontent>"

if (-not $(Test-Path -LiteralPath $OutPathRoot)) {
    New-Item $OutPathRoot -Force -ItemType Directory | Out-Null
}

#region AUTHENTICATION
# AUTHENTICATIONGet VARIABLESBearer $tenantIdToken =for "376e33ca-d656-4e46-8bcb-7d5ba898ae66"authentication $ClientIdagainst =Graph ""
$ClientSecret = ""API
$Body = @{
    "tenant"        = $TenantId
    "client_id"     = $ClientId
    "scope"         = "https://graph.microsoft.com/.default"
    "client_secret" = $ClientSecret
    "grant_type"    = "client_credentials"
}

$Params = @{
    "Uri"         = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
    "Method"      = "Post"
    "Body"        = $Body
    "ContentType" = "application/x-www-form-urlencoded"
}
$AuthResponse = Invoke-RestMethod @Params
$Header = @{
    "Authorization" = "Bearer $($AuthResponse.access_token)"
}

#endregion AUTHENTICATION






# GETGet DRIVEDrive ID of the Site
$Params = @{
    "Method"      = "Get"
    "Uri"         = "https://graph.microsoft.com/v1.0/sites/$SiteID/drive"
    "Headers"     = $Header
    "ContentType" = "application/json"
}
$DriveID = $(Invoke-RestMethod @Params | where { $_.name -eq $LibraryName }).id

# HOLEGet ALLEall FILESfiles AUSfrom DEMthe SHAREPOINTSharePoint ORDNERfolder
$Params = @{
    "Method"      = "Get"
    "Uri"         = "https://graph.microsoft.com/v1.0/sites/$SiteID/drives/$DriveID/root/children"
    "Headers"     = $Header
    "ContentType" = "application/json"
}
$SPFiles = $(Invoke-RestMethod @Params).Value

Select the option how you want to work with the file(s)

Afterwards, the files can be either all downloaded, downloaded individually or only the content can be viewed. Accordingly, the appropriate code piece must be selected.

Download all files

# ALLEDownload FILESall HERUNTERLADENthe files
foreach ($File in $SPFiles) {
    if ($File.'@microsoft.graph.downloadUrl') { # Schliesst Ordner aus
        $Params = @{
            "Method"      = "Get"
            "Uri"         = $File.'@microsoft.graph.downloadUrl'
            "ContentType" = "application/json"
            "OutFile"     = "$OutPathRoot\$($File.name)"
        }
        Invoke-RestMethod @Params
    }
}

Download one file

# EINZELNESDownload FILEonly HERUNTERLADENone file
$File = $SPFiles[1]
$Params = @{
    "Method"      = "Get"
    "Uri"         = $File.'@microsoft.graph.downloadUrl'
    "ContentType" = "application/json"
    "OutFile"     = "$OutPathRoot\$($File.name)"
}
Invoke-RestMethod @Params

Get the content of one file

# NURGet DENthe INHALTcontent EINESof FILESa HOLENfile
$File = $SPFiles[1]
$Params = @{
    "Method"      = "Get"
    "Uri"         = $File.'@microsoft.graph.downloadUrl'
    "ContentType" = "application/json"
}
$Content = Invoke-RestMethod @Params
$Content