Archive/Move files based on Modified Date range to another Library Using PowerShell while retaining Metadata

Hi,
I am trying to archive files from a SharePoint 2010 document library by moving them to another library that's a dedicated archive/folder/library. The files to be moved are selected based on their modified date column value that should range between any time
in the past to January 1st 2012. 
Also, to be able to retain the tags and cloumn values after the move. Open in explorer does not bring along the user added tags.
I tried to edit this script
$WebURL = "http://mysite.com/";
$ListDisplayName = "Crawl Test Library";
$ArchiveFolderName = "Crawl Test Library Archive";
function moveItems ()
trap
#make sure we dispose of these in the event of an error to avoid memory leaks:
write-host "Error - disposing of objects...";
$Web.Dispose();
$Site.Dispose();
[Microsoft.SharePoint.SPSite] $Site = New-Object Microsoft.SharePoint.SPSite($WebURL);
[Microsoft.SharePoint.SPWeb] $Web = $Site.OpenWeb();
[Microsoft.SharePoint.SPList] $List = $Web.Lists[$ListDisplayName];
$FolderToMoveTo = $List.RootFolder.Url + "/" + $FolderName;
$ItemMoveCount=0;
$Query = New-Object Microsoft.SharePoint.SPQuery;
$Query.Folder = $list.RootFolder;
$camlQuery = "<Where><Leq><FieldRef Name='Modified' /><Value Type='DateTime'>2012-01-01T00:00:00Z</Value></Leq></Where>"
$Query.Query = $camlQuery
$Query.RowLimit = 2200; #limit query because of large folder
$List.GetItems($Query) |
Where {$_.ContentType.Name -ne "Folder"} |
foreach-object {
#Line below will simply output to console and demonstrates another .NET call
[System.String]::format("Moving Item {0} with ID {1}...",$_.Name, $_.ID.ToString());
$Web.GetFile($_.Url).MoveTo([System.String]::format("{0}/{1}",$FolderToMoveTo,$_.Name));
write-host "Success...";
$ItemMoveCount++;
write-host "==============================================================================";
write-host "Complete! -> Moved " $ItemMoveCount " Items to directory " $FolderName;
write-host "==============================================================================";
#dispose:
$Web.Dispose();
$Site.Dispose();
#garbage collection
[GC]::Collect()
to do that but it doesn't seem to work. I am no guru in powershell yet so any help is appreciated.
Thanks.

This solution gets the job done. Much thanks to
Ian Hayse
NB...The Modified and Created dates are gonna reflect runtime dates now 
$web = Get-SPWeb "http://sharepointed.com/"
$list = $web.Lists["Shared Documents"]
$spQuery = New-Object Microsoft.SharePoint.SPQuery
$spQuery.ViewAttributes = "Scope='Recursive'";
$spQuery.RowLimit = 2000
$caml = '<Where><Lt><FieldRef Name="Created" /><Value IncludeTimeValue="TRUE" Type="DateTime">2014-01-01T04:06:45Z</Value></Lt></Where> '
$spQuery.Query = $caml
do
$listItems = $list.GetItems($spQuery)
$spQuery.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
$listTotal = $listItems.Count
for ($x=$listTotal-1;$x -ge 0; $x--)
try
$listItems[$x].CopyTo("http://sharepoint/Docs/Documents/"+ $listItems[$x].name)
Write-Host("DELETED: " + $listItems[$x].name)
$listItems[$x].Recycle()
catch
Write-Host $_.Exception.ToString()
while ($spQuery.ListItemCollectionPosition -ne $null)

Similar Messages

  • Can ditto select files based on modification date?

    Hi. I'm trying to use ditto to make backups. I would like to have it select only files modified after a certain date. Is there a way to do this?
    I noticed the bom (bill of materials) option... can that be used for this purpose somehow? Not quite sure how best to create a BOM that includes only files based on modification date.
    Any suggestions? Thanks
    Eric

    ditto doesn't provide a way to select only files modified after a certain date -- but find does; see the "-newer" and "-newerXY" options. Using find, you can generate a BOM file listing files that have been modified after a certain date.
    Then you can pass that BOM file to ditto.
    Powerbook G4 1GHz   Mac OS X (10.3.9)  

  • Query based on a date range

    I want to query based on a date range. I wrote the following EJB QL:
    "select object(a) from ActionItems as a where a.dueDate
    between ?1 and ?2"
    But when I deployed the application to Oracle's EJB server, I got the following error:
    Auto-deploying biogen.jar (No previous deployment found)... Invalid type for expression (a.dueDate BETWEEN ?1 AND ?2)
    EJB QL statement : 'select object(a) from ActionItems as a where a.dueDate between ?1 and ?2'
    EJB QL method : public abstract java.util.Collection ActionItemsLocalHome.findByDueDateRange(java.sql.Date,java.sql.Date) throws javax.ejb.FinderException
    at com.sun.ejb.ejbql.parser.EjbQLParser.parse EjbQLParser.java:218)
    at com.sun.ejb.ejbql.EjbQLDriver.parse(EjbQLDriver.java:86)
    at com.sun.ejb.sqlgen.SQLGenerator.generateSQLForEjbQLQueries(SQLGenerator.java:704)
    It works fine for a number range, but does not work for a date range.
    Any one has an idea on how to write a correct EJB QL for a query based on date range?
    Thanks.
    Jingzhi

    Re-posted. Please help!

  • Creation of internal table dynamically based on the Date Range entered

    Hi SAPgurus,
    I have been facing one issue i.e creation of internal table dynamically based on the date range entered in the selection screen. For example the date range I am giving as 06/2006 to 08/2006, it should display the Fieldcatelog dynamically, this part i have completed but the only issue I am facing is to populate the sales data into that fields.
    Right now my program is displaying the ALV like this.
    Ex:
    <b>CSR    District   06/2006  07/2006  08/2006  totals</b>      
    Shiva      New York                             10.00
    Shiva      new york                             30.00
    Shiva      new york                             40.00
    but it should display like this
    <b>CSR    District 06/2006 07/2006 08/2006 totals</b>
    Shiva  New York  10.00   30.00 40.00
    80.00                 
    Please help me in this scenario, how to acheive like this..
    Thanks & Regards,
    Sivaram Kandula

    Hi Sivaram,
                 I also got the same requirement . i saw rich and your code whatever you have uploaded.i have created dynamic internal table but i am facing the issue to populating the data to my dynamic internal table.
    Sivaram, can you please explain your code after this.
    *<dyn_table>
    *tab_item.
      LOOP AT tab_item.
        ASSIGN COMPONENT 1 OF STRUCTURE <dyn_wa> TO <dyn_table>.
        ASSIGN COMPONENT 2 OF STRUCTURE <dyn_wa> TO <dyn_table>.
    *    <dyn_wa> = tab_item-bztxt.
    *    <dyn_wa> = tab_item-total.
    *    APPEND <dyn_wa> TO <dyn_table>.
    **    <dyn_wa> = tab_item-total.
    **    ASSIGN tab_item-bezei  TO <dyn_wa>.
    *  APPEND <dyn_table>.
      ENDLOOP.
    how you are puting the loop at tab_item. but tab_item is already commented.
    can you send me the code after that.
    i am sending some part of my code.
    CALL METHOD cl_alv_table_create=>create_dynamic_table
       EXPORTING
         it_fieldcatalog = gt_fCAT1
       IMPORTING
         ep_table        = new_table.
    ASSIGN new_table->* TO <dyn_table>.
       create data new_line like line of <dyn_table>.
       assign new_line->* to <dyn_wa>.
    select vbeln
            fkart
            vkorg
            vtweg
            fkdat
            spart
            fksto
            from vbrk
            client specified
            into table gt_vbrk
            where mandt = sy-mandt
            and fkart in ('ZF5','ZFR')
            and vkorg = '1100'
            and vtweg = '20'
            and fkdat in s_fkdat
            and spart = '06'
            and fksto = ' '.
       if gt_vbrk[] is not initial.
      select  vbeln
              fkimg
              prsdt
              netwr
              matnr
              arktx
              werks
              mwsbp
              from vbrp
              client specified
              into table gt_vbrp
              for all entries in gt_vbrk
              where vbeln = gt_vbrk-vbeln
              and werks in s_werks
              and matnr in s_matnr.
      endif.
    select mnr ltx spras from t247
    into table it_t247
    where spras = 'E'.
    data: lv_month1 type vbrp-prsdt,
           name1(3) type c,
           s_month type string,
            s_month1 type string,
             s_month2 type string.
    *      lv_netwr1 type vbrp-netwr,
    *          lv_mwsbp1 type vbrp-mwsbp.
          loop at gt_vbrp into gs_vbrp.
            gs_final2-matnr = gs_vbrp-matnr.
            gs_final2-arktx = gs_vbrp-arktx.
            gs_final2-fkimg = gs_vbrp-fkimg.
           lv_month1 = gs_vbrp-prsdt.
            read table it_t247 into wa_t247 with key mnr = lv_month1+4(2).
            if sy-subrc eq 0.
            name1 =  wa_t247-ltx.
            endif.
             concatenate  name1
                       lv_month1(4) into s_month SEPARATED BY '_' .
             CONCATENATE S_MONTH 'QTY' INTO S_MONTH1 SEPARATED BY ''.
              CONCATENATE S_MONTH 'VALUE' INTO S_MONTH2 SEPARATED BY ''.
             gs_final2-month = s_month.
              lv_netwr1 = gs_vbrp-netwr.
            lv_mwsbp1 = gs_vbrp-mwsbp.
            gs_final2-MONTH_QTY = S_MONTH1.
            GS_FINAL2-MONTH_VAL = S_MONTH2.
            gs_final2-value = lv_netwr1 + lv_mwsbp1.
           append gs_final2 to gt_final2.
           clear: gs_final2. "lv_name2.
           endloop.
           if gt_final2[] is not initial.
             sort gt_final2 by matnr month ascending .
             loop at gt_final2 into gs_final2.
            gs_final2_01 = gs_final2.
         collect gs_final2_01 into gt_final2_01.
        endloop.
           endif.
       ENDIF..
    Regards
    Ankur

  • Sharepoint List Retention Policy based on Modified Date

    How do I implement a Sharepoint List Retention Policy that deletes list items that haven't been modified in X days?
    I've tried to create a retention policy in Sharepoint, but I only get the option to base the policy on:
    Created Date
    Declared Record
    I need the policy to be based on Modified Date, a standard date field that appears against all lists & document libraries. Is there a configuration change I can make to cause Modified Date to appear in the list of available fields on the Retention Policy
    dialog window?
    Thanks.

    Veda, thanks but I'm not really a hardcore C# coder.
    We found more elegant solution was to create a List View which returns all records that should be deleted, based on our own custom deletion criteria, and then create an very simple SSIS Package in Visual Studio using the
    Sharepoint Connectors for SSIS to delete all Sharepoint List Items returned from that List View. The Sharepoint Destination Connector has a delete operation.
    This worked for us and didn't require any coding.

  • Used Migration Assistant to successfully transfer PC files to Mini. However file creation or modified date does not transfer. Date of creation is listed as day of transfer.  I would gratefully appreciate any help in solving this,

    Used Migration Assistant to successfully transfer PC files to Mini. However file creation or modified date does not transfer. Date of creation is listed as day of transfer.  I would gratefully appreciate any help in solving this?

    I have the same problem; used Migration Assistant to transfer all my pix from PC to MacbookPro, however dates of pix were not transferred. Date created as the date of transfer. Cannot sort my pix according to date.
    Anybody has an answer?

  • Writing modified date of a document library item through CSOM.

    I´m working on an application which is replicating files from one document library to another. Since it is a replication, I want the modified date to be preserved when I copy the file from the source library to the target, so that the user will see the real
    modified date in the target library and not the date of the replication run.
    I access SharePoint through the client side object model and I have been able to set the modified date on a SharePoint 2010 on-premise using the following straght-forward code:
    var listItem = list.GetItemById(id);
    context.Load(listItem);
    context.ExecuteQuery();
    listItem["Modified"] = "03/11/1999";
    listItem.Update();
    context.ExecuteQuery();
    Unfortunately when I execute the same code on any other SharePoint (2013 On-Premise, 2013 Online or 2010 Online) the code will execute without any errors, but the modified date will not be changed at all.
    My actual question is: Is there any possibility to change the modified date throught CSOM on all of these SharePoint-versions?

    I got a work around for this problem..
    Before updating the Modified, Modified By values, First we need to Disable the version settings for document library. Once the fields updated then again we need to enable the version settings. 
    find the updated code below..
                                          //Disable Version settings for DOC LIB
    before update Metadata
                                            _List.EnableVersioning
    = false;
                                            _List.Update();
                                            _cContext.ExecuteQuery();
                                           ListItem item = newFile.ListItemAllFields;
                                           _cContext.Load(item);
                                            //Updating Metadata Created,
    CreatedBy, Modified, Modified By
                                             item["Created"]
    = "8/10/2013 7:04 PM";
                                             item["Author"] = CreatedUserValue;
                                             item["Modified"] = "8/10/2013 7:04 PM";
                                             item["Editor"] = ModifiedUserValue;
                                             item.Update();
                                            _cContext.ExecuteQuery();
                                            //Enable Version settings
    for DOC LIB after update Metadata
                                               _List.EnableVersioning
    = true;
                                              _List.Update();
                                            _cContext.ExecuteQuery();
    Rajendra

  • Is it possible to have 2 different output config XML files and index the data into 2 endeca apps using the same indexing component ProductCatalogSimpleIndexingAdmin

    Hi ,
    We have a catalog that defines 2 types of products (they have too many different properties), so wanted to keep them on two different MDEX engines and serve the applications requests. Here DB catalog and front end ATG application is same for both the MDEX instances.
    Is it possible to have 2 different output config XML files and index the data into 2 endeca apps using the same indexing component ProductCatalogSimpleIndexingAdmin?
    Thanks
    Dev

    Hi, also have had some problem some monthes ago - I created separete component ProductCatalogSimpleIndexingAdminSecond. After that one of my colleage gave me some advice:
    The creating separate component like ProductCatalogSimpleIndexingAdmin for the second IOC is possible way for resolving your situation. But I afraid that this way will be required creating mane duplicates for already existed components.
    In my opinion the better way is the following:
    starting from AssemblerApplicationConfiguration and ApplicationConfiguration component. It contains details for connecting between ATG and Endeca. Of course you should configure different components for different Endeca Apps.
    After that:
    Find all components that uses AssemblerApplicationConfiguration and ApplicationConfiguration. Customize these components for using one or another  *Configuration component depending on what index works. (many variants released it: the most simple global custom component with flag.)
    Then customize the existed ProductCatalogSimpleIndexingAdmin. Using one or another IOC  and setting the flag in global custom component when index started. You can add some methods into your custom ProductCatalogSimpleIndexingAdmin like:
    Execute baseline index for both IOC (one by one)
    Execute baseline for IOC 1
    Execute baseline for IOC 2.
    Note: you should be afraid about incremental (partial) index in this configuration. But resolving conflicts in incremental index should be done after full implementation these changes.
    Regards

  • When i open my Canon RAW-files with preview or transfer them to another program using preview they change to color despite the fact that they where all shot in B/W... How to change this?

    When i open my Canon RAW-files with preview or transfer them to another program using preview they change to color despite the fact that they where all shot in B/W... How to change this?

    I shoot only RAW - no JPEG-files except those visualizing the files on my memorycard or computer. I think i have to refine my question;
    1. I know there is possible to make B/W HDR-images.
    2. I know the best HDR images are based on RAW-files.
    3. When i transfer the images in question to a HDR software they change, so when i view them in the software (either Preview or the HDR software) they are suddenly viewed (and processed) in color.
    4. This never happend on my PC so i know it has to do  with either Finder or Preview.
    5. Do i have to make all my B/W HDR-images on the PC or is it a way for me to change how Finder/Preview show/alter my images?

  • How to update managed metadata column for all file in document library using powershell

    Hi,
    How to update managed metadata column for all file in document library using powershell?
    Any help on it.
    Thanks & REgards
    Poomani Sankaran

    Hi TanPart,
    I have changed the code which you have give in order to get the files from SharePoint 2010 Foundation  Document Library.But i am getting below error in powershell.
    Property 'ListItemCollectionPosition' cannot be found on this object; make sure it exists and is settable.
    Could you tell me which is the issues in it?
    See the code below.
    $web = Get-SPWeb http://ntmoss2010:9090/Site
    $list = $web.Lists["DocLib"]
    $query = New-Object Microsoft.SharePoint.SPQuery
    $query.ViewAttributes = "Scope='Recursive'";
    $query.RowLimit = 2000
    $caml = '<Where><Contains><FieldRef Name="Title" /><Value Type="Text">Process Documents/Delivery</Value></Contains></Where>' +
            '<OrderBy Override="TRUE"><FieldRef Name="ID"/></OrderBy>'
    $query.Query = $caml
    do
        $listItems = $list.GetItems($query)
        $spQuery.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
        foreach($item in $listItems)
            #Cast to SPListItem to avoid ambiguous overload error
            $spItem = [Microsoft.SharePoint.SPListItem]$item;
            Write-Host $spItem.Title       
    while ($spQuery.ListItemCollectionPosition -ne $null)
    Thanks & Regards
    Poomani Sankaran

  • File Count with selected date range

    Hi,
    Our requirement is to get the file count with selected date by the user from two sharepoint date time controls i.e. dtp1 and dtp2 into the data table. I am able to get the file count of specific folder from Pages library through below code. Now need to get
    the selected date range from two date time picker controls and check with the item created by is within the date range. If yes I need to get the file count.
    So please share your ideas/thoughts to do the same.
    SPList list =
    wikiweb.Lists["Pages"];
                        SPFolderCollection oFolders
    = list.RootFolder.SubFolders["foldername"].SubFolders;
                        DataTable dt
    = new DataTable();
                        dt.Columns.Add("Column1");
                        DataRow dr;
                        if (oFolders.Count
    > 0)
                            foreach (SPFolder oFolder in oFolders)
     if (!oFolder.Name.Equals("Forms"))
                                    dr
    = dt.NewRow(); 
    dr["Column1"] = oFolder.ItemCount.ToString();
    dt.Rows.Add(dr);
    Regards,
    Sudheer
    Thanks & Regards, Sudheer

    Hi,
    I have modified the code as below
    if((DateTime)(oFolder.Item.File.TimeCreated>dtFromDate.SelectedDate)&&(DateTime)(oFolder.Item.File.TimeCreated<dtToDate.SelectedDate))
    But still it is throwing the error.
    Please share your ideas on the same.
    Regards,
    Sudheer
    Thanks & Regards, Sudheer

  • SSIS package to order all the CSV files based on their date of creation/modification mentioned in a filename and load the least recent file in oracle Destination

    HI,
    I need a help for creating SSIS package which has flat file source (specifically , delimited csv files) which are placed in a shared folder
    having file names as  File_1_2015-04-30 08:54:13.900.csv, File_2_2015-04-30 07:54:13.900.csv.
    So, I wanted to use foreach loop to find out the oldest file amongst that(through script task) and need to transform that file in Oracle Destination. After that, I want to archive that file and need to continue this action uptil the most recent file gets
    loaded in destination.
    So, Could you guys please guide me?
    Thanks in advance

    I'd say you need two loops, one to cycle through all the files and collect their names. Then sort them based on your criterion
    Perhaps you can start by seeing http://www.sqlis.com/sqlis/post/Looping-over-files-with-the-Foreach-Loop.aspx
    Collect the file names into a Recodset Destination, then shred it http://www.sqlis.com/sqlis/post/Shredding-a-Recordset.aspx
    perhaps you need an outer loop to iterate over each file to compare the files for dates.
    Do each piece and post here where you needed to stop.
    Arthur
    MyBlog
    Twitter

  • Metrics generation based on (birth) date ranges

    Hello all,
    Am a beginner in OBIEE. Am trying to derive some metrics out of birthdate information I have. Its a 2 part question.
    1) Count of occurrence of birthdates.
    Its a simple count(*) query and this I was able to get it done in OBIEE - all the formatting is done
    Eg:
    source data
    *19300203*
    *19300203*
    *18301203*
    *19600204*
    metrics out of that
    *19300203 - 2*
    *18301203 - 1*
    *19600204 - 1*
    2) Count of birthdate based on period distribution.
    Now, categorizing the date range in to 3 distributions.
    a) before 1900
    b) 1900 to 1950
    c) after 1950
    output will should be something like -
    before  1900 - 1
    *1900 to 1950 - 2*
    after 1950   - 1
    I tried a lot and searched in forums and now stuck really and could not proceed with this type of data generation model.
    Can you please show some pointers on how I can proceed with this?
    Many thanks.

    Hi,
    Bit tricky without more details of your model, but im guessing you have a date dimension and a fact with your count measure.
    I'd start in answers, create some 'Bins' on your date column or manually write a case statement to create the attribute you want to group the counts by (ie :
    when date < 1900 then 'Before 1900' else when < 1951 then '1900 to 1950' else 'after 1950)
    If your happy with this result, I'd move the case statement back into the RPD BMM layer as a logical column in your Date dimension and go from there. This way the grouping of dates is available across other reports and is not confined to a specific formula in the report you are currently working on.
    HTH, let us know if you get stuck.

  • Quicktime Mov File size reduce after Data Recovery

    Following a Data Recovery from Apple Care, most of my video files have been reduced to 120x90 pixels making them unwatchable. The Format is Apple Photo-JPEG, 120x90, Millions 16-bit Integer (Big Endian), Stereo, 48000 kHz with a Data Size of 15.16 MB. Other QT mov files bring up the following message "The movie could not be opened" "A necessary data reference could not be resolved"
    Is there any way I can get the Dimensions back to 640x480 and can the necessary data reference be resolved.
    My Quicktime Player is Version 7.6.4 (518.35)

    Is there any way I can get the Dimensions back to 640x480 and can the necessary data reference be resolved.
    Assuming the original data is in tact, the normal work flow would be to either reset/resize the movie's "Current Size" setting and re-save the file store the new setting using QT Pro or use QT Pro, an alternative QT application, or a third-part application to re-compress the file to the proper dimensions but this approach, depending on settings, can degrade the video. As to the missing "references," depending on the required "references," it might be possible to re-link/restore things if you know enough about the file structure (which I don't).

  • PowerShell Script to Delete Files Based on Current Date

    I know by using Get-Date PowerShell will look at the current date.  I would like to make a very basic PS Script which will delete a file older than 8 days based on the current day.  I believe using a if/then function will be necessary. 
    I am very new to scripting so Im not sure how the syntax is written.  All help appreciated.

    Yes, use -Recurse to get subfolders too:
    $Folder = "C:\Users\Me\Backups"
    Get-ChildItem -Path $Folder -Recurse |
    Where { $_.LastWriteTime -lt [DateTime]::Today.AddDays(-8) } |
    Sort LastWriteTime |
    Remove-Item $_ -Force -Confirm:$false
    Sam Boutros, Senior Consultant, Software Logic, KOP, PA http://superwidgets.wordpress.com (Please take a moment to Vote as Helpful and/or Mark as Answer, where applicable) _________________________________________________________________________________
    Powershell: Learn it before it's an emergency http://technet.microsoft.com/en-us/scriptcenter/powershell.aspx http://technet.microsoft.com/en-us/scriptcenter/dd793612.aspx

Maybe you are looking for

  • Qosmio turns off when download any programs

    I just bought the Qosmio and i started to use the internet for the first time and i wanted to download the new msn massenger but the computer turned off automatically, I tried to download other programmes but it keeps turning off. Please help i'm rea

  • Field Separator as Space

    Hi Sdners,            My interface is Idoc to Flat file. I am facing a problem when I am doing content conversion for receiver communication channel.          My receiver structure is                                                    abc 123 xyz    

  • Entering your email twice on sign-up forms

    I have a sign-up form for membership for a client, and they want it so the user enters their email address twice (in case they make a typo). This is such a common functionality, is there any on-page validation in CF or simple technique for this that

  • How to make a HyperCard-like application

    I've written several japplets that do useful things, but they have been "single-screen" applications. This time I have to program a japplet that has multiple screens. On the 1st screen, the user makes a selection. Upon hitting "Next", the 2nd screen

  • MRS Upgrade from 500 to 800

    Hi Gurus, For a client we are going for ECC 5.0 to ECC 6.0 upgrade with EHP 5 and as a part of this upgrade we are going from MRS 500 to MRS 800. Could you please let me know are there any difficultues to go from MRS 500 to 800? During configuration,