Move list item to a folder in SharePoint Online using PowerShell

There are many examples on how to move files using PowerShell in SharePoint Online document libraries. At least at the time of writing, there’s no guidance on how to programmatically move list items to folders within lists in SharePoint Online. If you have enabled folder creation in a SharePoint online list and would like a script to programmatically move items to it, here it is:

cls

#region declarations
$siteUrl = "https://tenant.sharepoint.com/sites/StarkEnterprises"
$listTitle = "Suites"
$itemId = 8 #you will likely have additional logic to get this programatically but this is just an example
$destFolderServerRelativeURL= "/sites/StarkEnterprises/Lists/Suites/Mark 1-10/" #destination folder
#endregion

#region move item
Connect-PnpOnline -Url $siteUrl -Interactive
$listItem = Get-PnPlistItem -List $listTitle -Id $itemId
$srcItemUrl = $listItem.FieldValues.FileRef #complete item url
$srcFolderServerRelativeURL = $listItem.FieldValues.FileDirRef #source directory
$destFileUrl = $srcItemUrl.Replace($srcFolder, $destFolderServerRelativeURL);

#Assumes the folder exists but may want to check for it first
Move-PnPFile -SourceUrl $srcItemUrl -TargetUrl $destFileUrl
#endregion

The prerequisites for running the script are:

  1. You will need to have the PnP PowerShell module installed
  2. You will need to have enabled Folder creation for lists via your list settings page
  3. You will of course need to have contribute or higher permissions to both the source and destination to be able to execute this Move operation

You can also refer to this post if you’d like to programmatically create folders using PowerShell: Create folder in a SharePoint Online list using PowerShell

Thanks and hope this helps someone!

This entry was posted in Uncategorized and tagged , , , , , , , . Bookmark the permalink.

Leave a comment