2

I have write some PowerShell script to get double items in different lists. I would like to remove the oldest item. I will check this by the "modified" date. How can I sort the results by "modified" date?

#Add SharePoint PowerShell SnapIn if not already added 
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) { 
    Add-PSSnapin "Microsoft.SharePoint.PowerShell" 
} 

$siteCollection = Get-SPSite "https://portal.myCompany.net/teams/siterequests/"

 foreach($spSourceWeb in $siteCollection.AllWebs)
 { 
     $spSourceLists = $spSourceWeb.Lists 

     foreach($spSourceList in $spSourceLists)
     {
         $spSourceList.Items | where {$_['Title'] -eq '440-10011'} | foreach { 
            "modified date: " + $_["Modified"] + " found item: " + $_.Title  + " , in list: " + $spSourceList.Title
         }       
      }
 }

So I would like to sort this $spSourceList.Items | where {$_['Title'] -eq '440-10011'} on the column "modified". I would like to have the oldest modified date as first.

2 Answers 2

1

You can use Sort-Object -Property for sorting the result

$spSourceList.Items | where {$_['Title'] -eq '440-10011'} | Sort-Object -Property Modified ....
4
  • I try these scripts but the results are the same: $spSourceList.Items | where {$_['Title'] -eq '440-10011'} | Sort-Object -Property Modified -descending | foreach { "modified date: " + $_["Modified"] + " found item: " + $_.Title + " , in list: " + $spSourceList.Title } or $spSourceList.Items | where {$_['Title'] -eq '440-10011'} | Sort-Object -Property Modified | foreach { "modified date: " + $_["Modified"] + " found item: " + $_.Title + " , in list: " + $spSourceList.Title }
    – Ola
    Oct 27, 2014 at 13:30
  • 1
    Try this inside the for each loop $spSourceList.Items | Sort-Object -Property Modified | Format-Table $_.Title,$_["Modified"] Oct 27, 2014 at 13:36
  • With this last script I got this error: Cannot index into a null array.
    – Ola
    Oct 27, 2014 at 13:39
  • $spSourceList.Items | where {$_['Title'] -eq '440-10011'} | Sort-Object -Property $_["Modified"] Oct 27, 2014 at 13:44
1

I think better solution is to get filtered and sorted items from list using CAML query:

$qry = New-Object Microsoft.SharePoint.SPQuery;
$qry.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>440-10011</Value></Eq></Where><OrderBy><FieldRef Name='Modified' Ascending='TRUE' /></OrderBy>";
$listItems = $spSourceList.GetItems($qry);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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