|
| 1 | +# Ensure the Site Assets Library is created |
| 2 | + |
| 3 | +Author: [Phillip Allan-Harding](https://github.com/phillipharding/) |
| 4 | + |
| 5 | +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. |
| 6 | + |
| 7 | +Reference: ['ensure' commands #1427](https://github.com/pnp/office365-cli/discussions/1427) |
| 8 | + |
| 9 | +- gets the collection of lists at the site url supplied |
| 10 | +- if a list with the title "Site Assets" isn't found |
| 11 | + - gets an access token for the tenant's SharePoint resource |
| 12 | + - calls the _api/web/Lists/EnsureSiteAssetsLibrary REST endpoint to create the Site Assets library |
| 13 | +- returns the existing or created SPList as a JSON object |
| 14 | + |
| 15 | +```powershell tab="PowerShell Core" |
| 16 | +function EnsureSiteAssetsLibrary { |
| 17 | + param ( |
| 18 | + [Parameter(Mandatory)][string]$siteUrl |
| 19 | + ) |
| 20 | +
|
| 21 | + <# |
| 22 | + send a HTTP POST request to: |
| 23 | + https://<tenant>.sharepoint.com/sites/<sitename>/_api/web/Lists/EnsureSiteAssetsLibrary/ |
| 24 | + which returns an SPList |
| 25 | + #> |
| 26 | + $list = $null |
| 27 | +
|
| 28 | + Write-Host "-> Ensure Site Assets library: $siteUrl" |
| 29 | + $lists = o365 spo list list --webUrl "$siteUrl" -o json | ConvertFrom-Json |
| 30 | + if (($null -ne $lists) -and ($null -ne $lists.value)) { |
| 31 | + $list = $lists.value | Where-Object { $_.Title -eq "Site Assets" } |
| 32 | + } |
| 33 | +
|
| 34 | + if ($null -eq $list) { |
| 35 | + Write-Host "...Creating Site Assets library" |
| 36 | +
|
| 37 | + try { |
| 38 | + $resource = ($siteUrl -split "/")[2] |
| 39 | + $accessToken = o365 util accesstoken get --new --resource "https://$resource/" |
| 40 | + } |
| 41 | + catch { |
| 42 | + throw "!! Unable to get AccessToken for EnsureSiteAssetsLibrary at '$siteUrl'`nERROR: $_" |
| 43 | + } |
| 44 | + try { |
| 45 | + $headers = @{ "Authorization" = "Bearer $accessToken"; "Accept" = "application/json;odata=nometadata" } |
| 46 | + $endpoint = "$siteUrl/_api/web/Lists/EnsureSiteAssetsLibrary/" |
| 47 | + $response = (Invoke-RestMethod -Uri $endpoint -Headers $headers -Method POST) |
| 48 | + $list = $response |
| 49 | +
|
| 50 | + Write-Host "...Created: $($list.Id)" |
| 51 | + } |
| 52 | + catch { |
| 53 | + throw "!! Unable to EnsureSiteAssetsLibrary at '$siteUrl'`nERROR: $_" |
| 54 | + } |
| 55 | + } else { |
| 56 | + Write-Host "...Already exists: $($list.Id)" |
| 57 | + } |
| 58 | +
|
| 59 | + $list |
| 60 | +} |
| 61 | +``` |
0 commit comments