Skip to content

Instantly share code, notes, and snippets.

@AshFlaw
Last active June 19, 2023 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AshFlaw/18a794af9b01d19350cc7c25fe02bf19 to your computer and use it in GitHub Desktop.
Save AshFlaw/18a794af9b01d19350cc7c25fe02bf19 to your computer and use it in GitHub Desktop.
SharePoint Online: Update file metadata in document library
function Update-CSOMFileMetadata {
param (
[Parameter(Mandatory=$True)]
$SiteURL,
[Parameter(Mandatory=$True)]
$FileServerRelativeUrl,
$CreatedBy,
$ModifiedBy,
$CreatedOn,
$ModifiedOn,
[System.Management.Automation.PSCredential]
$Credential
)
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"
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Credential.UserName,$Credential.Password)
# Get the File
$File = $Ctx.Web.GetFileByServerRelativeUrl($FileServerRelativeUrl)
$Ctx.Load($File)
$Ctx.ExecuteQuery()
# Get 'Created By' and 'Modified By' Users and ensure they exist in the target site collection
$Author = $Ctx.Web.EnsureUser($CreatedBy)
$Ctx.Load($Author)
$Editor= $Ctx.Web.EnsureUser($ModifiedBy)
$Ctx.Load($Editor)
$Ctx.ExecuteQuery()
$ListItem = $File.ListItemAllFields
if ($null -ne $CreatedBy) {$Listitem["Author"] = $Author}
if ($null -ne $ModifiedBy) {$ListItem["Editor"] = $Editor}
if ($null -ne $CreatedOn) {$ListItem["Created"] = $CreatedOn}
if ($null -ne $ModifiedOn) {$ListItem["Modified"] = $ModifiedOn}
$ListItem.Update()
$Ctx.ExecuteQuery()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment