FunctionsPublic/New-GraphList.ps1



<#
.SYNOPSIS
Creates a new SharePoint list
 
.DESCRIPTION
Creates a new SharePoint list with the specified columns according to the specified list type.
 
.PARAMETER accessToken
A Microsoft Graph API access token with the required permissions
 
.PARAMETER sharePointSiteID
The SharePoint site where the list should be added to
 
.PARAMETER listName
The name of the list
 
.PARAMETER listType
The type of the list
 
.PARAMETER listColumnsJSON
Optional additional columns to add to the list as PSObject format.
#>

function New-GraphList
{
    param(
        [parameter(Mandatory=$true)][psobject]$accessToken, 
        [parameter(Mandatory=$true)][string]$sharepointSiteID, 
        [parameter(Mandatory=$true)][string]$listName, 
        [parameter(Mandatory=$false)][string]$listType = "genericList",
        [parameter(Mandatory=$false)]$listColumns
    )

    if($null -eq $listColumns)
    {
        $sendBody = @{
            "displayName" = "$($listName)";
            "list" = @{ "template"= "$($listType)" }
            } | ConvertTo-Json 
    }
    else 
    {
        $sendBody = [ordered]@{
            "displayName" = "$($listName)";
            "list" = @{ "template"= "$($listType)" };
            "columns" = $listColumns
            } | ConvertTo-Json -Depth 10
    }
    
    $responseBody = Invoke-RestMethod `
        -Uri "https://graph.microsoft.com/v1.0/sites/$($sharepointSiteID)/lists" `
        -Headers @{"Authorization" = "Bearer $($accessToken.AccessTokenCredential.GetNetworkCredential().password)"} `
        -Body $sendBody `
        -ContentType "application/json" `
        -Method POST

    if($null -eq $responseBody)
    {
        return $null
    }
    else
    {
        return $responseBody.value
    }
}