Welcome to an article on how to copy documents from one SharePoint Document library to another based on Created Date using PowerShell.
I searched the web everywhere and didn’t find this script so I thought of writing it down for my readers. Sometimes we need some of our files in another document library based on some interval of period from the date it was created.
You have a choice, using this script which will move the files based on your input as in from how many days from today you want the files which were created or uploaded during this time zone.
How? Let’s see it.
- Open Windows PowerShell Modules as an Administrator.
Code:
Call the Web
- $web = Get-SPWeb "Add your web collection here"
Get the library
- $list = $web.Lists["Add your library name here"]
- $spQuery = New-Object Microsoft.SharePoint.SPQuery
- $spQuery.ViewAttributes = "Scope='Recursive'";
- $spQuery.RowLimit = 2000
Get the Current Date here
Add the date from when you want the photos to be pulled as in from today until how many last days
- $twoday = $a.AddDays(-4)
- $v = Get-Date $twoday -Format s
Query the list
- Write - Host $v
- $caml = '<Where><Gt><FieldRef Name="Created" /><Value Type="DateTime">' + $v + '</Value></Gt></Where>'
- $spQuery.Query = $caml
- do {
- $listItems = $list.GetItems($spQuery)
- $spQuery.ListItemCollectionrank = $listItems.ListItemCollectionrank
- # Get the count of items queried accoring to our condition
- $listTotal = $listItems.Count
- Write - Host $listTotal
- for ($x = $listTotal - 1; $x - ge 0; $x--)
- {
- try
- {
- $listItems[$x].CopyTo("Add your library complete link here" + $listItems[$x].name)# It will run stating the name of the item
- Write - Host("Updated: " + $listItems[$x].name)
- $listItems[$x].Update()
- }
- catch
- {
- Write - Host $_.Exception.ToString()
- }
- }
- }
- while ($spQuery.ListItemCollectionrank - ne $null)
- Save the above code in a notepad as .ps1 file.
- Run the code on the Windows PowerShell Modules.
- It will display the number of files moved from the number of days selected.
- As I have updated 4 days, so it will move all the files which have been created during the last 4 days.
It will be so quick that you don’t take much time and effort on this, thereby saving a lot of time and effort. Run the script and you have all the files moved at once.