Ensure the Site Assets Library is created
Summary
There are occasions when creating a new modern SharePoint site using the CLI/REST API that the Site Assets library isn't created, use this script to ensure that the Site Assets library is created. Reference: 'ensure' commands #1427
- gets the collection of lists at the site url supplied
- if a list with the title "Site Assets" isn't found
- gets an access token for the tenant's SharePoint resource
- calls the _api/web/Lists/EnsureSiteAssetsLibrary REST endpoint to create the Site Assets library
- returns the existing or created SPList as a JSON object
function EnsureSiteAssetsLibrary {
param (
[Parameter(Mandatory)][string]$siteUrl
)
<#
send a HTTP POST request to:
https://<tenant>.sharepoint.com/sites/<sitename>/_api/web/Lists/EnsureSiteAssetsLibrary/
which returns an SPList
#>
Write-Host "-> Ensure Site Assets library: $siteUrl"
$list = m365 spo list get --webUrl $siteUrl --title "Site Assets" | ConvertFrom-Json
if ($null -eq $list) {
Write-Host "...Creating Site Assets library"
try {
$resource = ($siteUrl -split "/")[2]
$accessToken = m365 util accesstoken get --resource "https://$resource" --output text
}
catch {
throw "!! Unable to get AccessToken for EnsureSiteAssetsLibrary at '$siteUrl'`nERROR: $_"
}
try {
$headers = @{ "Authorization" = "Bearer $accessToken"; "Accept" = "application/json;odata=nometadata" }
$endpoint = "$siteUrl/_api/web/Lists/EnsureSiteAssetsLibrary/"
$response = (Invoke-RestMethod -Uri $endpoint -Headers $headers -Method POST)
$list = $response
Write-Host "...Created: $($list.Id)"
}
catch {
throw "!! Unable to EnsureSiteAssetsLibrary at '$siteUrl'`nERROR: $_"
}
} else {
Write-Host "...Already exists: $($list.Id)"
}
$list
}
Check out the CLI for Microsoft 365 to learn more at: https://aka.ms/cli-m365
Source Credit
Sample first appeared on Ensure the Site Assets Library is created | CLI for Microsoft 365
Contributors
Author(s) |
---|
Phillip Allan-Harding |
Martin Lingstuyl |
Disclaimer
THESE SAMPLES ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.