Monday, November 26, 2012

SharePoint Managed Paths Explained

Let me document the Frequently Asked Questions on SharePoint Managed Paths during my training sessions:

What is Managed Path in SharePoint?

A managed path is a location within a web application in which you can have site collections. When you create a web application, there are two managed paths created with it. The first managed path is called the Root "/" path of explicit inclusion type. The second is called "sites" with wildcard inclusion path. SharePoint 2010 My Site host comes with "Personal" Wildcard managed path.

Why We need Managed Paths in SharePoint?
Managed Paths in SharePoint used to group multiple sites based on some criteria. Also helps to maintain a logical structure in SharePoint. Say, You want to group all Sales department sites, then you can have: http://company/sales/Site1/ , http://company/sales/Site2/, etc.


SharePoint managed path examples:
Lets take an example. A typical SharePoint URL could be: "http://company.com/sites/Sales/apac/"
Where
  • http://company.com - Web Application
  • Sites-  Managed path
  • Sales - Site collection
  • apac - Sub-site

Explicit vs Wildcard
There are two Types of Managed Paths we can create:
  1. Explicit inclusion : Path can be explicitly used for only one site collection. (E.g. http://company/sites/hr) and no site collections can be created underneath the path. (But sub-sites can be created under site collection)
  2. Wildcard inclusion: If you want to create site collections underneath a specific path, choose "Wildcard" (for example, "Sites" in http://server/sites/). Unlimited site collections can be created under the given path.
sharepoint 2010 define managed path

How to Configure Managed Paths for SharePoint 2010 Web Applications?
Managed Paths are defined at web application level. You can have different paths for different web applications. They cannot be defined for host header site collections. To define managed path in SharePoint 2010, Go to:
  1. Central Administration >> Application Management.
  2. In Application Management page, click on Manage Web Applications
  3. Click the Web application for which you want to configure Manage Paths 
  4. Now from the ribbon, click Managed Paths.
  5. From here you can configure Managed Paths for a particular web application.
  6. Once you are done with managed paths, click OK.

sharepoint web application managed path

Nested Managed paths
is it possible to nest a managed path under another managed path? Yes! You can create nested managed paths! Say for E.g. You create a Managed Path "/sites/" , then You create managed path as "/sites/sales". Now you can create site collections under each of these paths.

But you cannot create a site collection under /sites/  as "Sales", because once you create the managed path "Sales" under "Sites" it is marked as reserved!

SharePoint Managed Path Limits
Its a best practice to have SharePoint managed paths < 20. As per SharePoint 2010 Software boundaries and limits  20 Managed Paths can be created per Web application.You can expect performance issues if you exceed this limit!

Can I Create Site collections Under Root?
By default, Root Managed Path (/) is created as Explicit inclusion, which means you can create only one site collection at the root of the web application. However you can delete and Re-create it with Wildcard inclusion to enable site collections under Root.

How to Change site collection managed path
If you want to change the managed path of your site collection, You have to:
  • Backup your site collection
  • Delete your site collection
  • Restore your site collection with new managed path
Refer my post: How to Change Site Collection URL for step by step instructions.

What if I delete the Managed path in use?
Answer: Your SharePoint Sites under the specific managed path will result: HTTP 404 Page Not Found!

SharePoint Managed path not in list?
Managed Path Not available in Create Site Collection Page, After deleting the site collection which was occupying the specified managed path already ? Refer my article for the solution: Managed Path Not available

How to Create/Delete SharePoint Managed path Programmatically with C# object model or Powershell? 
To Manage SharePoint managed paths in C# object model and in PowerShell, Refer my article: Programmatically Get/Create/Delete Managed Paths in SharePoint


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Saturday, November 24, 2012

Export SharePoint Survey Results to Excel

Requirement: is to consolidate and analyze a SharePoint survey results by exporting the data to Excel Spreadsheet.

Solution: Go to the survey overview page, Export SharePoint survey results to excel by clicking  Actions >> Export to Spreadsheet
Export SharePoint Survey Results to Excel
SharePoint 2010 Survey Export to Spreadsheet missing?
Received end-user support tickets with the complaint: SharePoint 2010 survey export to spreadsheet is missing!

Export to Excel functionality in SharePoint surveys is available under the Overview view only! not on any other views like Show all Responses (Allitems.aspx) or Graphical Summary view!! so make sure you are on "Overview" page to export SharePoint survey data to spreadsheet.

Export to excel menu is missing in SharePoint survey overview view also?
There could be some other factors:
  • We must have Office Application installed on our client machine.
  • Make sure "Client Integration" is enabled for the the web application. Go to Central Administration > Application Management > Authentication Providers , select the target web application and enable Client Integration.
  •  If you modified the overview view, closed the web part, You must Restore the closed web part to get "Export to excel". Adding survey list doesn't bring export to excel option!
  • I have seen, export to spreadsheet option is missing in SharePoint 2010 surveys, when I customized the Overview.aspx. Also it happens when I closed the original webpart on overview.aspx. Restoring the closed web part to the page resolves this issue, but adding survey list to the page doesn't!! 
  • Make sure, the Overview view is set as default view!

SharePoint survey doesn't export all columns when you export to excel?
SharePoint 2010 Survey had 50 questions, and when I was trying to export that to spreadsheet, got only 20 questions! To resolve, edited the overview view by clicking site actions >> Edit Page >> Modify Shared Web Part >> Edit Current View >> Check All Questions required)

URL Shortcut to Export to Excel:
Internally, Export to Excel options makes RPC call to owssvr.dll, So, we can directly hit the URL in the browser with List & View GUID parameters:

Syntax: http://sharepoint-site-url/_vti_bin/owssvr.dll?CS=65001&Using=_layouts/query.iqy&List={List-GUID}&View={view-GUID}

E.g. http://sharepoint.crescent.com/sites/marketing/_vti_bin/owssvr.dll?CS=65001&Using=_layouts/query.iqy&List=%7BF84685F2%2DF803%2D41F0%2D9B05%2D42D2A208FD0F%7D&View=%7B23582AF3%2D7E9D%2D4ADF%2D9F93%2D1A5DEED3A633%7D

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Thursday, November 22, 2012

SharePoint SQL Server Database Went Offline Mode - How to Bring it back to Online?

Suddenly SharePoint Database Went Offline.
sql server database is offline
Analyzed Event Logs and found Database went offline because: Backup failure.

SQL Server How to Bring Database Online?
Alright, How to Bring it back to Online? one line T-SQL!

ALTER DATABASE STS_G1WSS01_1385353007 SET ONLINE

sql server bring database online
Database is up and we are back to business!


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Tuesday, November 20, 2012

SharePoint 2010 Keyboard Shortcuts

Did you know we can use keyboard shortcuts in SharePoint 2010? Yes, As part of Accessibility standards, SharePoint 2010 offers keyboard shortcuts.

How to use these shortcuts? use ALT + [key] and then ENTER (To do click action!)

Here’s the list of useful keyboard shortcuts: [Key] can be:
  •   S – Go to the search box
  •   W – Login dropdown, Shared Documents - Press once again to switch between these items.
  •   X – Skip to main content (hidden)
  •   Y – Skip Ribbon Commands
  •   / – Site Actions Menu
  •   1 – Home
  •   6 – Help
  •   3 – View All Site Content

These shortcut keys are real Timer savers! and my favorite pick is:  ALT+3, ENTER to get "View All Site Content"

There are lot of other shortcuts, you can use in: Calendar View, Standard toolbar, formatting toolbar, Web Part Page, Web Part Maintenance Page, etc. Find More Shortcuts here: http://office.microsoft.com/en-us/sharepoint-server-help/keyboard-shortcuts-HA010369395.aspx


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, November 19, 2012

Closed Web Parts in SharePoint - How to Find, Restore and Delete

Closed Web Parts? What are they?

When users don't need a particular web part on the page, they click on Edit drop down from Web Part Menu, and choose "Close" instead of Delete. They prefer Close rather Delete which is obvious!

Technically, When you close a Web Part, It doesn't appears on the screen. But still running on the background and eating up the resources. Its a best practice to delete the closed web parts. Because, closed Web parts takes up the memory and could cause impact on performance.
sharepoint closed web part

How to Find closed web parts from SharePoint Interface

How to find closed Web Parts? Open the Web Part page in Web Part Maintenance Mode (Just append ?contents=1 at the end in address bar). E.g. http://SharePoint.com/sites/sales/default.aspx?contents=1  and look for "No" value under Open on Page? column.
find closed web parts sharepoint 2010
 

How to Delete Closed Web Parts using SharePoint Interface

From the Web Part Maintenance Mode, choose the web parts which are in closed mode (Open on Page?  column value "No") and click on "Delete" from the Toolbar.
sharepoint 2010 delete closed web part

How to Stop Users from Closing a Web Part?
Simple! Go to the web part properties, In Advanced tab Disable "AllowClose" check-box!

How to Restore Closed Web Parts using SharePoint Interface

Accidental close of web parts may happen while you edit web part pages. Here is how to Restore closed web parts.
  1. Go to Site Actions >> Edit Page
  2. Click on "Add a Web Part" link
  3. Scroll down and select "Closed Web Parts" (In MOSS 2007, Go to Advanced Web Part gallery and options)
  4. Once you click, it will show all the web part which are closed on this page.
  5. Choose the web parts and click on "Add" to bring closed web part to the page.  how to restore closed webpart in sharepoint 2010
    To delete a closed web part, Restore it first and then delete it!

How to Find and Delete Closed Web Parts With PowerShell:

Well, If its a single page, We can use web part maintenance page to delete closed web parts. But for the whole site, its cumbersome. Closed web parts list can be retrieved by reading SharePoint Content Databases directly! But as per Microsoft's Advice lets not do it. Lets use PowerShell instead. This script will create a CSV file for logging Pages and closed web parts before deleting it.

#Add SharePoint Snap-in
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$OutputReport ="C:\ClosedWebParts.csv"
$SiteURL="http://intranet.crescent.com"
#Write Header to CSV File 
"Web Part Name,Site URL, Page URL" | out-file $OutputReport
 
#Get all Webs
#$WebsColl = Get-SPWebApplication | Get-SPSite -Limit All | Get-SPWeb -Limit All
$WebsColl = Get-SPSite $SiteURL | Get-SPWeb -Limit All

#Iterate through webs
foreach ($Web in $WebsColl) 
{
    write-host "Processing Web:"$Web.URL
    #Get All Pages from site's Root into $AllPages Array
    $AllPages = @($web.Files | Where-Object {$_.Name -match ".aspx"})
 
    #Search All Folders for Pages
    foreach ($Folder in $web.Folders)
    {
       #Add the pages to $AllPages Array
       $AllPages += @($Folder.Files | Where-Object {$_.Name -match ".aspx"})
    }
  
    #Iterate through all pages
    foreach($Page in $AllPages)
    {
        $WebPartManager = $web.GetLimitedWebPartManager($Page.ServerRelativeUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
    
        #Array to Hold Closed Web Parts 
        $ClosedWebParts = @()
        foreach ($webPart in $webPartManager.WebParts | Where-Object {$_.IsClosed})
        {
            $Result = "$($webpart.Title),$($web.Url),$($page.Url)"
            Write-Host "Found a Closed Web Part: "$Result -f Green
            $Result | Out-File $OutputReport -Append
            $ClosedWebParts += $webPart.ID
        }
 
        #If the closed web part is found
        If($ClosedWebParts)
        {
            #Checkout if required
            if ($Page.RequiresCheckout) 
            { 
                if ($Page.CheckOutStatus -ne "None") 
                {  
                    write-host "Overriding Checkout..."
                    $Page.UndoCheckOut()
                }
                $Page.CheckOut()
            }
            
            #Remove the web part from page
            foreach ($WebPart in $ClosedWebParts)
            {
                 Write-Host "Deleting closed web part at $($web.Site.Url)/$($page.Url)"
                 $WebPartManager = $Page.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)       
                 $WebPartManager.DeleteWebPart($WebPartManager.webParts[$webPart])
            }          
            
            #Check-in                 
            if ($Page.CheckOutStatus -ne "None") 
            { 
                $Page.CheckIn("Deleted web part")
                $Page.Publish("")
            }
            
            #Approve if required
            if ($Page.ParentList.EnableModeration) { $Page.Approve("") }
        }
    }
 }        

So the rule of Thumb is: If you don't need a web part in a page, Delete it! You can export the web part and use it later, if you want.


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Friday, November 16, 2012

Hidden Screen Capture Utility in Windows 7

Windows 7 comes with an In-Built Screen recorder: Problem Steps Recorder to record screen with series of screenshots and text. Its greatly helpful when we want to reproduce end-users issues and troubleshoot.

How to open : Problem Steps Recorder? Go to Run >> Type "PSR"
It launches the nifty utility.
With this tool, we can record screen by clicking on "Start Record", add comments in middle, pause and then resume recording. Once done, on clicking "Stop Record", it creates a ZIP file with .MHT file with all steps.



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Wednesday, November 14, 2012

Drive Space Monitoring using PowerShell Script

In SharePoint servers monitoring disk space is a common administrator task. Because, SharePoint servers may run out of disk space from SharePoint, IIS Logs, SQL Server transaction logs or even from SharePoint content (If you don't have Quotas enabled!)

There are lot of first-party, third-party utilities available, such as SCOM to Monitor disk space. What if you don't have such tools in your environment? no worries, Just PowerShell can do the monitoring of disk space! PowerShell disk space monitoring can be a cost saver too!

Schedule this PowerShell script in windows task scheduler("powershell.exe D:\scripts\DriveSpaceMonitor.ps1" . Make sure PowerShell is in your "Path" environment variable!) on hourly basis. Script will run every hour and mail only when the drive's free space goes below the provided threshold value.

Here is the PowerShell script for disk space monitoring:

#Purpose: Script to check the drive space in the server against the threshold value and triggers an alert
#powershell script for disk space monitoring 
$computer = get-content env:computername; #Get the server name
$percentWarning = 50; # Store the percentage warning threshold
$disks = Get-WmiObject -ComputerName $computer -Class Win32_LogicalDisk -Filter "DriveType = 3";

$mailbody = "The following drive(s) have less than $percentWarning% free sapce in Server: $computer`n`n";

$mailbody+="Drive`t`tTotalspace(GB)`t`t`Freespace(GB)`n --------------------------------------------------------------- `n";
$drivedata="";
$emailsubject="$computer - Low Disk Space Alert!";


# Code to send email to the SharePoint Administrator/Group
function SendEmail([string]$msg)
{
 $SMTPClient = new-object System.Net.Mail.smtpClient;
 $SMTPClient.host = "smtp.yourcompany.org"
 $MailMessage = new-object System.Net.Mail.MailMessage;
 $MailMessage.Subject = $emailsubject;
 $MailMessage.Body = $msg;
 $MailMessage.From = "DiskSpaceMonitor@crescent.com";
 $MailMessage.To.add("salaudeen.rajack@crescent.com");
 $SMTPClient.Send($MailMessage);
}

#The following block performs the core functionality
foreach($disk in $disks) 
{ 
 $deviceID = $disk.DeviceID; 
 [float]$size = $disk.Size; 
 [float]$freespace = $disk.FreeSpace;   
 $percentFree = [Math]::Round(($freespace / $size) * 100, 2); 
 $sizeGB = [Math]::Round($size / 1073741824, 2); 
 $freeSpaceGB = [Math]::Round($freespace / 1073741824, 2);   
 if($percentFree -lt $percentWarning) 
 { 
  $drivedata += "$deviceID`t`t $sizeGB`t`t`t$freeSpaceGB`n";

 } 
}

#Email to be sent only if any drive has free space less than threshold value
if($drivedata.length -gt 0)
{
 $msg=$mailbody+$drivedata;
 SendEmail($msg);
}

and see it in action! (I've changed the threshold to 50% for testing. It can be 10%-20% in general)

disk space powershell report
monitoring disk space with powershell
If you want to monitor for multiple servers, just use this trick:
#Array to hold list of Servers
$computers = @("ServerName1","ServerName2","ServerName3","ServerName4")

#Iterate through each server
foreach ($computer in $computers)
{
   #Place the above code inside
}
Alternatively, To get all SharePoint Servers, use:
#Get all SharePoint Servers
$servers = Get-SPServer | where { $_.role -ne "Invalid"}

foreach($computer in $servers)
{
    write-host $Computer.Name
}

How to Add Attachment:
#Attachment
$attachmentPath = "C:\Reports\MonthlyRpt.zip"

$Attachment = new-object System.Net.Mail.Attachment($attachmentPath) 
$MailMessage.Attachments.Add($Attachment) 

Tail: SharePoint 2010's Health analyzer has the rule to check "Drives are running out of free space." which can be utilized as well. But by default SharePoint health analyzer won't send email notifications and only display to users within Central Administration.

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Tuesday, November 13, 2012

Stop and Start SharePoint 2010 Services

In my Laptop with Windows 7, I've SharePoint 2010 Installed for my tryouts. I use it whenever I'm out of network connectivity.

Problem is: Not quite frequently I use SharePoint from my laptop, but SharePoint services starts automatically when I turn-on my laptop and eating up my resources especially RAM.(SharePoint is resource hungry! Huh)

What I want is: Stop all SharePoint services and start only whenever I require them. I used run a batch file (or we can go to Services console) to stop SharePoint, SQL Server and IIS Services. Here is my batch file.

@echo stopping SharePoint 2010 services
REM SharePoint 2010 Administration
net stop SPAdminV4  


REM SharePoint 2010 Timer
net stop SPTimerV4


REM SharePoint 2010 Tracing
net stop SPTraceV4

REM SharePoint 2010 VSS Writer
net stop SPWriterV4

REM SharePoint Server Search 14
net stop OSearch14

REM SharePoint Foundation Search V4
net stop SPSearch4 

REM SharePoint 2010 User Code Host
net stop SPUserCodeV4

REM IIS
iisreset /stop  /noforce

REM World wide Publishing
net stop w3svc 

REM SMTP service
net stop smtpsvc

REM SQL Server
net stop MSSQLSERVER

@pause



and the Start Script goes like:


@echo starting SharePoint 2010 services

REM SharePoint 2010 Administration
net start SPAdminV4 

REM SharePoint 2010 Timer
net start SPTimerV4

REM SharePoint 2010 Tracing
net start SPTraceV4

REM SharePoint 2010 VSS Writer
net start SPWriterV4

REM SharePoint Server Search 14
net start OSearch14

REM SharePoint Foundation Search V4
net start SPSearch4  

REM SharePoint 2010 User Code Host
net start SPUserCodeV4

REM IIS
iisreset /start 


REM World wide Publishing
net start w3svc  

REM SMTP service
net start smtpsvc

REM SQL Server
net start MSSQLSERVER

@pause


SharePoint 2013 services can be stopped and started using PowerShell also: How to Stop and Start All SharePoint 2013 Services using PowerShell

Later, I found a nice utility in Codeplex to do the same: SharePoint 2010 Service Manager at:http://sharepointserviceman.codeplex.com/
In addition to All SharePoint related services, this utility also provides option for disabling them on Start up.


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Monday, November 12, 2012

Delete All Items from List or Library using PowerShell

At times, we may have to delete all items from SharePoint list or library. We can get it done by going to "Manage Content and Structure" option as in my another article How to Remove All responses from SharePoint Survey

There may be situations, where we've to delete all items from SharePoint list programmatically. Here are the code snippets to achieve the same.

Delete All Items from SharePoint List or Library using PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$WebURL = "http://portal.crescent.com/credit/"
$ListName="WorkflowHistory"

#Get web List and List Items
$Web = Get-SPWeb $WebURL
$List = $Web.Lists[$ListName]
$ListItems = $List.items
Write-host "Total Items in the List:"$List.ItemCount

#Iterate through each Item in the list
foreach ($Item in $ListItems)
{
    $List.GetItemByID($Item.id).Delete()
    Write-host "Deleted Item: $($item.id)" -foregroundcolor Red
} 
Traditional Way of deleting Items from end to avoid: "Collection was modified" Error
for ($i=$listItems.Count-1;$i -ge 0; $i-–)
{
Write-Host("Deleted: " + $listItems[$i].name)
 $listItems[$i].Delete()
}

One-Line PowerShell script to remove all items from SharePoint List:
(Get-SPWeb http://your-sharepoint-site).Lists["ListName"].Items | % { $_.ParentList.GetItemById($_.ID).Delete() }

Filter and Delete List Items:
We can filter the list items using CAML and perform the same delete operation. Here it goes:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

$url = "http://sharepoint.crescent.com/"
$web = Get-SPWeb $url
#Get the List
$list = $web.Lists["Tasks"]

#CAML Filter Query
$CAMLQuery="<Where><Eq><FieldRef Name='Status' /><Value Type='Choice'>Completed</Value></Eq></Where>"

$SPQuery=New-Object Microsoft.SharePoint.SPQuery
$SPQuery.ViewAttributes = "Scope='Recursive'"  #Get all items from Folders also!
$SPQuery.Query=$CAMLQuery
$SPQuery.RowLimit  = 10000; 

#Get the List items based on Filter 
$result=$list.GetItems($SPQuery)

#Delete the items from list
$result | % { $list.GetItemById($_.Id).Delete()  }

Delete All Items from SharePoint list Programmatically using C# Object Model:
Same code can be re-written in C# to delete list items programmatically.
           using (SPSite oSPsite = new SPSite("http://sharepoint"))
               {
                    using (SPWeb oSPWeb = oSPsite.OpenWeb())
                    {
                        oSPWeb.AllowUnsafeUpdates = true;

                        // Get the List
                        SPList oSPList = oSPWeb.Lists["Tasks"];

                        for (int i= oSPList.ItemCount-1; i >=0; i--)
                        { 
                            oSPList.Items[i].Delete(); 
                        }

                        oSPWeb.AllowUnsafeUpdates = false;

                    }
                }
Bulk Delete using ProcessBatchData:
   using (SPSite oSPsite = new SPSite("http://sharepoint"))
               {
                    using (SPWeb oSPWeb = oSPsite.OpenWeb())
                    {
                        // Get the List
                        SPList oSPList = oSPWeb.Lists["Tasks"];

                        StringBuilder batchString = new StringBuilder();
                        batchString.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");

                        foreach (SPListItem item in oSPList.Items)
                        {
                            batchString.Append("<Method>");
                            batchString.Append("<SetList Scope=\"Request\">" + Convert.ToString(item.ParentList.ID) + "</SetList>");
                            batchString.Append("<SetVar Name=\"ID\">" + Convert.ToString(item.ID) + "</SetVar>");
                            batchString.Append("<SetVar Name=\"Cmd\">Delete</SetVar>");
                            batchString.Append("</Method>");
                        }

                        batchString.Append("</Batch>");
                        oSPWeb.ProcessBatchData(batchString.ToString());

                    }
                }
PowerShell script to delete in Bulk from SharePoint list:
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

Function global:Get-SPWeb($url)
{
  $site= New-Object Microsoft.SharePoint.SPSite($url)
        if($site -ne $null)
            {
               $web=$site.OpenWeb();
        
            }
    return $web
}

$WebURL ="http://sharepoint.crescent.com/sites/operations/us/"
$ListName ="DSF_Transactions"
$BatchSize = 1000  #Lets delete 1000 items at a time

#Get the web object
$web = Get-SPWeb $WebURL
 
#Get the List
$list = $web.Lists[$ListName]


while ($list.ItemCount -gt 0)
{

    Write-host "Total Number of Items:"$list.itemcount
    
    $StringBuilder = New-Object System.Text.StringBuilder
    $StringBuilder.Append("<?xml version=`"1.0`" encoding=`"UTF-8`"?><Batch>") > $null

    $BatchCount=0
    
    foreach($item in $List.Items)
    {
    $StringBuilder.Append("<Method><SetList Scope=`"Request`">$($list.ID)</SetList><SetVar Name=`"ID`">$($item.ID)</SetVar><SetVar Name=`"Cmd`">Delete</SetVar></Method>") > $null
    $BatchCount++
        if($BatchCount -ge $BatchSize) { break } #Break from this foreach loop
    } 

    $stringbuilder.Append("</ows:Batch>") > $null

    $web.ProcessBatchData($StringBuilder.ToString()) > $null
    $list.Update()
}
Don't forget to Add, when you are deleting from a library:
<SetVar Name=`"owsfileref`">$($item.File.ServerRelativeUrl)</SetVar>
Deleting SharePoint list items using ProcessBatchData method sends items to Recycle bin!
Delete Vs Recycle: Will the Deleted Items goes to Recycle bin?
No! Delete method doesn't send files to Recycle bin. But the Recycle Method does! So, call the Recycle method , if you want the deleted items to be sent to Recycle bin.

using (SPWeb web = siteColl.AllWebs["Sales"])
{
  SPList list = web.Lists["Tasks"];
  SPListItem item = list.Items[GUID];
  item.Recycle();
}
You can also: Save list as template (without content), Delete the list and Re-create from the list template! - Provided if there is no workflow/event receiver associated with the list.


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


How to Create SQL Server Alias for SharePoint

In My SQL Server best practices for SharePoint 2010, I wrote a point on SQL Server Alias. Let me elaborate that by going little deep on configuring SQL alias for SharePoint.

Why We need SQL Alias for SharePoint?
Because, SharePoint SQL alias best practice! Creating SQL Alias for SharePoint enables you to change the Database Server of your SharePoint Farm! This will be a great help during disaster recovery, virtualizations or migrations. Also its difficult to move SharePoint to a different SQL Server, If you don't use SQL Alias.
When disaster strikes, just change SQL Server alias that SharePoint references.

Where to Setup SQL Alias? 
SQL Alias to be set on All SharePoint Servers except DB Server (SQL Server!)
CliConfig.exe located at C:\windows\system32\cliconfg.exe in Windows 2003. For Windows 2008 and 2012, (or in 64 bit OS), its located at C:\windows\syswow64\cliconfg.exe

You don't need to install anything on your machine, as this SQL Alias Configuration utility comes with Windows. You can create it with SQL Server Config Manager also, When you have SQL Server  installed it on the SharePoint server.

How to Setup SQL Alias
Launch SQL Server Client Network Utility as stated above.
SQL Server Alias for SharePoint
Select the "Alias" tab and click on "Add" button.

Select "TCP/IP" and provide the name for alias. Then  fill in the host name of your database server and select the "Dynamically determine port" check box.
SharePoint SQL alias best practice
Now you have defined your SQL alias name. Click "OK" to complete.

How to Verify the SQL Alias Created?
We've created the SQL Alias. Lets make sure, Our SQL Alias works. Here is how: Login to any of your servers where you created SQL Alias (E.g. SharePoint Web Front end Server)
  1. Create an empty text file, say: Test.txt, then rename it from Test.txt to Test.udl
  2. Double-click the test.udl file. From the Data Link Properties screen,  Enter your SQL alias name, choose your authentication method, and click on "Test connection" button. You should get "Successful" message.
  3. Also, in the database drop down, you should see the list of databases from your SQL Server! 
How to test SQL Server Alias

OK, Alias is configured on all SharePoint WFE/APP Servers. Now what?
Its a best practice to setup SQL alias during initial farm setup. if not  re-run SharePoint Configuration wizard on a established farm . If your SharePoint is already up and running, launch SharePoint Products and technologies wizard and configure your SharePoint farm with the new SQL Alias.

Don't want to use SQL Server Alias? Run stsadm.exe -o renameserver -oldservername <oldname> -newservername <newname> on all servers to change the name of the specified server in the configuration database if the SQL Server is renamed.


You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Friday, November 9, 2012

Change/Move Site collection to a Different Managed Path

Created site collection under wrong Managed Path? Now want to move the site collection to another managed path? Unfortunately there is no way, other than:
  • Backup your source site collection
  • Delete the source site collection
  • Restore the site collection with the desired target URL!
There is no other way to change managed path for SharePoint site collection. These steps also applies If you want to rename Site collection URL. This can be done with either STSADM or with PowerShell.

For detailed step by step instructions see my post: How to Change Site Collection URL .

You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


You might also like:

Related Posts Plugin for WordPress, Blogger...