简体   繁体   中英

Upload file to SharePoint Online with metadata using PowerShell

I'm trying to upload a batch of files to SharePoint Online using PowerShell and include metadata too (column fields). I know how to upload files, this works fine:

$fs = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
$fci= New-Object Microsoft.SharePoint.Client.FileCreationInformation
$fci.Overwrite = $true
$fci.ContentStream = $fs
$fci.URL = $file
$upload = $list.RootFolder.Files.Add($fci)
$ctx.Load($upload)
$ctx.ExecuteQuery()

and I know how to edit fields/columns, this works:

...   
$item["project"] = "Test Project"
$item.Update()
...
$list.Update()
$ctx.ExecuteQuery()

but I don't know how to tie the two together. I need to get an item reference to the file I've uploaded so that I can then update the item/file's metadata. As you can guess, PowerShell and SharePoint are all new to me!

The following example demonstrates how to upload a file and set file metadata using SharePoint CSOM API in PowerShell:

$filePath = "C:\Users\jdoe\Documents\SharePoint User Guide.docx" #source file path
$listTitle = "Documents"
$targetList = $Context.Web.Lists.GetByTitle($listTitle) #target list

#1.Upload a file
$fci= New-Object Microsoft.SharePoint.Client.FileCreationInformation
$fci.Overwrite = $true
$fci.Content = [System.IO.File]::ReadAllBytes($filePath)
$fci.URL = [System.IO.Path]::GetFileName($filePath)
$uploadFile = $targetList.RootFolder.Files.Add($fci)

#2.Set metadata properties
$listItem = $uploadFile.ListItemAllFields
$listItem["LastReviewed"] = [System.DateTime]::Now
$listItem.Update()

$Context.Load($uploadFile)
$Context.ExecuteQuery()

@vadimGremyachev --- THANKS! Question... I have a CSV of files that I'm uploading. One of the CSV columns is a metadata tag which I'm using a hash to convert to its GUID from the termstore. of the 500 files, I have ~5 files that refuse to set the value in SPO. It does NOT throw an error. I know the GUID is correct in my hash because other documents are tagged with the shared value from the HASH.

    #2.Set metadata properties
    $listItem = $upload.ListItemAllFields
    $listItem["LegacySharePointFolder"] = $row.LegacySharePointFolder
    $listItem.Update()
    $listItem["Customer"] = $TermStoreCustomerHash[$row.CUSTOMER]
    $listItem.Update()

Thanks!

You can add metadata to the existing record without incrementing the version. #2.Set metadata properties

    $listItem = $upload.ListItemAllFields

item.File.CheckOut();

$listItem["LegacySharePointFolder"] = $row.LegacySharePointFolder
$listItem.Update()
$listItem["Customer"] = $TermStoreCustomerHash[$row.CUSTOMER]
$listItem.Update()

item.File.CheckIn("",CheckinType.OverwriteCheckIn);

clientContext.ExecuteQuery();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM