A while ago I posted on how to display Sites or Site Collections using Content Search Web Part here.

Well, since CSWP periodically displays “Sorry, something went wrong”, users are not happy with this solution.

So, I wrote a PowerShell script to update a list called “Site Directory”, and placed it on the home page.  I then added one additional logic to get new site collections created from the previous day.  After adding the script to Task Scheduler, I didn’t have to worry about missing newly created site collections.

To get all of the site collections created from the previous day, I used:

$Today = [DateTime]::Today
$Yesterday = $Today.AddDays(-1)

$siteCollections = Get-SPWebApplication http://demosite.vee.local | Get-SPSite -limit ALL | where {$_.RootWeb.Created -ge $Yesterday}

Now keep in mind, $Today will return today’s date at midnight and the same goes for $Yesterday (yesterday’s date at midnight).  I pointed this out to make sure that when you schedule this script in the Task Scheduler, you set it to run accordingly.  And, of course, replace the Web application with your Web application.

Writing it to a list was pretty straightforward, I added a category to the list, so I would have an additional option to display different views on the page.

In this list (Site Directory), there’s a hyperlink column.  I wanted the users to click on the hyperlink using a display name instead of the URL.  So, the $hyperlink in the script, will display the “friendly name”(ex: Coffee Beans) instead of the URL (ex: http://demosite.vee.local/dept/coffee%20beans).

foreach($siteCollection in $siteCollections)

  $web.Title + "," + $siteCollection.Url + "," + $web.Created | Out-File -Encoding Default -Append -FilePath $outFile;

$newItem = @{}
$sites = Import-Csv -path $outFile

$web = Get-SPWeb "http://demosite.vee.local";
$list = $web.GetList("http://demosite.vee.local/lists/Site Directory");

foreach($site in $sites)
  $siteURL =  $site.URL
  if($siteURL -match "/apps/")
    $category = "APPS"
  elseif($siteURL -match "/dept/")
    $category = "DEPT"
    $category = "DEFAULT"
    $newItem = $list.items.Add();
    $newItem["Title"] = $site.'Title'
    $hyperlink = $site.URL + ", " + $site.Title
    $newItem["SiteURL2"] = $hyperlink
    $newItem["Category"] = $category

Well, since I made this change, the users are happy.  No complaints! 🙂