Last active
June 19, 2023 08:56
-
-
Save AshFlaw/18a794af9b01d19350cc7c25fe02bf19 to your computer and use it in GitHub Desktop.
SharePoint Online: Update file metadata in document library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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