Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

The following code seems to be working. Basically, I have multiple items in a document library and I need to run a cleanup PS. Do I need to add Dispose as I am not running under the Using context?

$webUrl = "http://Biochemistry.Lab.UOF/Sites/Research"
$web = Get-SPWeb $webUrl
$list = $web.Lists["CurrentResearch"]

$caml = "<Where><Contains><FieldRef Name=`"ResearchName`" /><Value Type=`"Text`">DNA PCR Test</Value></Contains></Where>"
$cQuery=new-object -TypeName "Microsoft.SharePoint.SPQuery"
$cQuery.Query = $caml
$myItems=null

$myItems = $list.GetItems($cQuery);
Write-Host ("Items returned = [" + $myItems.Count + "]")

if ($myItems.Count -gt 1)
{
for ($i=1; $i -le $myItems.Count; $i++)     
{
   if($i -ne 0)
   {                
      $myItems[$i].Delete();
      Write-Host "Deleted ";
   }
}
}
share|improve this question
    
Mike, instead of editing the answer into your question.. can you please post an answer instead? Currently, no one can see what you asked originally (without going to version history). If you post it as an answer people can upvote it as well. –  Kit Menke Oct 21 '11 at 23:54
add comment

2 Answers

up vote 2 down vote accepted

This is the working version.

$webUrl = "http://Biochemistry.Lab.UOF/Sites/Research"
$web = Get-SPWeb $webUrl
$list = $web.Lists["CurrentResearch"]

$caml = "<Where><Contains><FieldRef Name=`"ResearchName`" /><Value Type=`"Text`">DNA PCR Test</Value></Contains></Where>"
$cQuery=new-object -TypeName "Microsoft.SharePoint.SPQuery"
$cQuery.Query = $caml
$myItems=null

$myItems = $list.GetItems($cQuery);
Write-Host ("Items returned = [" + $myItems.Count + "]")

if ($myItems.Count -gt 1)
{
for ($i=1; $i -le $myItems.Count; $i++)     
{
   if($i -ne 0)
   {                
      $myItems[$i].Delete();
      Write-Host "Deleted ";
   }
}
}
share|improve this answer
add comment

SPQuery has a propery named RowLimit. Do you get the expected result when setting this property value to 1?

share|improve this answer
    
The code is working. Do I need to add Dispose method at the end? –  Mike conway Oct 21 '11 at 19:33
    
Yes, dispose the SPWeb: $web –  Anita Boerboom Oct 21 '11 at 19:41
    
i changed the for loop for ($i=0; $i -le $myItems.Count-1; $i++) now I dont get an error but it only deletes 2 files. Total count is 5 and I need to delete 4 of the items. –  Mike conway Oct 21 '11 at 19:52
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.