Before I get to the “looping through all documents” part of what I am trying to achieve, I am trying to update a single custom metadata field value on a document in a library. Ultimately I will loop through the entire library and change 4 different custom metadata fields on the documents based on sections of the document name.
I have done some fun and interesting things with powershell, but really struggling with interacting with the online sharepoint model after reading a lot of articles. There seems to be a few ways to skin the cat, but not successful yet with any.
Here is a simple example of one way I have tried to achieve this. In this case I am expecting that the $File.ListItemAllFields in about line 24 will give me access to all fields including the additional ones we have added to the library, but this technique seems to only expose a few fields (id title and GUID). I can update the exposed fields (ie code works on Title), but don’t understand why I cannot update any other fields eg MyCustomField below (and many others I have tried).
I get this error on trying to update other fields, even though this field absolutely exists:
Error Updating Metadata of the File! Exception calling “ExecuteQuery” with “0” argument(s): “Column ‘MyCustomField’ does not exist.
It may have been deleted by another user. /sites/Star/Shared Documents”
#Load SharePoint CSOM Assemblies
Add-Type -Path “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll”
Add-Type -Path “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll”
#Set parameter values
$SiteURL=“https://mycompany.sharepoint.com/sites/DocCentral” # modern sharepoint site!
$FileRelativeUrl="/sites/doccentral/Shared Documents/1000 Operations/ABC-OP-PR-1000_26 Woven Procedure.doc"
#Get Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = $Credentials
$File = $Ctx.web.GetFileByServerRelativeUrl($FileRelativeUrl)
#Set Metadata of the File
$ListItem = $File.ListItemAllFields
$ListItem[“MyCustomField”] = “Hello World” #Any other field outside of ID, Title and GUID not accessible after above line??
Write-host -f Green “File’s Metadata has been Updated Successfully!”
write-host -f Red “Error Updating Metadata of the File!” $_.Exception.Message