I based my code from this example it stated it had the ability to create list items with attachments from existing list items in a new list. I liked this example because I would like to archive old items on my list. I created a CAML Query that would look for items in the list with the "Archived" status. When I tested the query it worked perfectly. Then I inserted it in the code, and I don't think the code recognizes the query. When I run the code it will just make a copy of every list item in the source list, instead of "Archived" items only.
Does anyone know what I can do to get the code recognize the CAML Query and only create the items queried?
Update: both lists are Custom Lists if that changes anything
Remove-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
try
{
# REQUIRED: URL to source SharePoint site with list
$srcListSiteUrl = "http://testsrv/sites/home/pre-sales"
# REQUIRED: Name of source list.
$SourceListName = "Pre-SalesNew2"
# REQUIRED: URL to destination SharePoint site with list (can be the same site)
$dstListSiteUrl = "http://testsrv/sites/home/pre-sales"
# REQUIRED: Name of destination list.
$DestinationListName = "ArchivedPreSalesRecords"
# Finds the source SharePoint site and then appends "/lists/" and the list name to the URL.
$sourceListWeb = Get-SPWeb -identity $srcListSiteUrl
$sourceListUrl = $sourceListWeb.ServerRelativeUrl + "/lists/" + $SourceListName;
# Finds the destination SharePoint site and then appends "/lists/" and the list name to the URL.
$dstListWeb = Get-SPWeb -identity $dstListSiteUrl
$destinationListUrl = $dstListWeb.ServerRelativeUrl + "/lists/" + $DestinationListName;
# Finds the list at the URLs stored in the variables
$SourceList = $sourceListWeb.GetList($sourceListUrl);
$DestinationList = $dstListWeb.GetList($destinationListUrl);
$sourceSPListItemCollection = $SourceList.GetItems();
foreach($srcListItem in $sourceSPListItemCollection)
{
#CAML query
$camlQuery =
'<Where>
<Eq>
<FieldRef Name="StatusPreSales" />
<Value Type="Choice">Archived</Value>
</Eq>
</Where>'
$spQuery = new-object Microsoft.SharePoint.SPQuery
$spQuery.Query = $camlQuery
write-host "adding new item"
$newSPListItem = $DestinationList.AddItem();
foreach($spField in $srcListItem.Fields)
{
if ($spField.ReadOnlyField -ne $True -and $spField.InternalName -ne "Attachments")
{
$newSPListItem[$spField.InternalName] = $srcListItem[$spField.InternalName];
}
}
# Handle Attachments
foreach($leafName in $srcListItem.Attachments)
{
$spFile = $SourceList.ParentWeb.GetFile($srcListItem.Attachments.UrlPrefix + $leafName)
$newSPListItem.Attachments.Add($leafName, $spFile.OpenBinary());
}
$newSPListItem.Update()
}
}
catch
{
write-host $_.exception
}
finally
{
if($sourceListWeb -ne $null){$sourceListWeb.Dispose()}
if($dstListWeb -ne $null){$dstListWeb.Dispose()}
}