Using Microsoft.Graph PowerShell Module to Update a Sharepoint List

I've been working on a big VMware automation project for a customer who wants to use their Sharepoint site as the source of authority for configuration files.  They are using Microsoft Graph to give me access to that environment, so my permissions do not extend to the standard PnP.Powershell module and I've been learning the Microsoft.Graph module instead.

We came across an issue when using the new-MgSiteListItem cmdlet though, where we were getting error messages like "Field 'title' is not recognized."  In this case, there was a field called Title and the configuration that we'd passed the cmdlet specified Title, but the internal workings of the cmdlet were converting the first character to lowercase and thus the whole thing wasn't working.  But, there's an easy work-around!

The Microsoft.Graph PowerShell module has a catch-all cmdlet: Invoke-MgGraphRequest.  With it, you can use the Graph API directly, without having to worry about headers and authentication and stuff (since that part is managed by the Connect-MgGraph cmdlet)!  And fortunately, there's an easy-to-use API call that'll do exactly this!

So, the work-around is pretty easy.  First, I need to construct a new list item object.  If I had a list with these columns: Title, ReleaseDate, IMDBLink

I would do something like this:

$movie = new-object pscustomobject

$movie | Add-Member -Type NoteProperty -Name "Title" -Value "Spider-Man: No Way Home"

$movie | Add-Member -Type NoteProperty -Name "ReleaseDate" -Value "12/17/2021"

$movie | Add-Member -Type NoteProperty -Name "IMDBLink" -Value "https://www.imdb.com/title/tt10872600/"

Now that I've got my Sharepoint List Item object created, I need to wrap it up in an object that could contain the metadata that Sharepoint loves so much.  In this case, we only need a "fields" property, so I'll do it like this:

$sharepointItem = new-object pscustomobject

$sharepointItem | Add-Member -Type NoteProperty -Name "fields" -Value $movie

...and now we're ready to invoke that API call!

Invoke-MgGraphRequest -uri "v1.0/sites/$siteID/lists/$listID/items" -method POST -body ($sharepointItem | convertto-json)

And that's it!  The API is expecting that new row to be described in JSON using the structure that we created with the nested objects, so we simply convert that to JSON and pass it as the body of the API call!

P.S. That SiteID is the same SiteID that you'll use for any of the Graph powershell stuff.  I get my ListID by using: (Get-MgSiteList -siteId $siteID | ? {$_.displayName -eq "MyFavoriteMovies"}).id

Comments

Popular posts from this blog

Clone a Standard vSwitch from one ESXi Host to Another

PowerShell Sorting by Multiple Columns

Deleting Orphaned (AKA Zombie) VMDK Files