Saturday, February 28, 2015

"MOSS MA not found" Error on Configuring User Profile Synchronization Connection

Problem: 
I had a requirement to setup new SharePoint 2010 environment. After everything, created user profile service application to get users synced. Got "MOSS MA not found" error on adding a synchronization connection while configuring user profile service application.
"MOSS MA not found" Error on Configuring User Profile Connection
Solution:
Go to Services Console (Start >> Administrator Tools >> Services) and then start these services.
  • Forefront Identity Manager Synchronization Service
  • Forefront Identity Manager Service Synchronization Service 
Restarting "User profile synchronization service" from SharePoint Central Administration, Services on Server page fixed the problem in an another case.

Other things to look at:
  • Firewall - FIM service should be accessible via port 5725 on local machine.
  • Remove and Re-Add Farm Admin to 'Administrators' section with Full Control in User profile Service application
  • Server Reboot!


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


Remove User From All Sites in SharePoint using PowerShell

Delete user from all site collections in SharePoint 2010/2013 using PowerShell:
Some times, we may need to delete a particular user from all site collections. Say for e.g. Employee leaves the company! Here is how to remove a user from all SharePoint sites using PowerShell.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

Function Delete-UserFromAllSites([string]$WebAppURL, [string]$UserID)
{
    #Get All Site collections
    $SitesColl = Get-SPWebApplication $WebAppURL | Get-SPSite -Limit All

    foreach($Site in $SitesColl)
    {
        write-host "Processing site:" $Site.RootWeb.URL
        
        #Check if user Exists in the site collection
        $User = $Site.RootWeb.SiteUsers | Where-Object {$_.LoginName -eq $UserID}
           
        #If user account found
        if($User -ne $null)
        {
            #Remove User from the Site
            Remove-SPUser $UserID -web $Site.RootWeb.URL -confirm:$false
            write-host "Removed user from site collection:"$Site.RootWeb.URL -f Green
        }        
    }    
}

#Variables for processing
$WebAppURL = "https://Portal.Crescent.com/"
$UserID="Crescent\DaveP"

#Call the function
Delete-UserFromAllSites $WebAppURL $UserID
 
This will scan and delete SharePoint user from all site collections in the given web application.

To delete multiple users from all site collections, just store user accounts in an array and call the PowerShell function. E..g
#Array to store user accounts
$userNames= ("domain\user1", "global\user2", "domain\user3")
#Iterate through the array
foreach($user in $userNames)
 {  
   #Call the function
   Delete-UserFromAllSites "http://sharepoint.crescent.com" $user 
 }


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


Hide Overwrite existing files Option of Upload Document Page in SharePoint 2010

Requirement:
Uncheck and Hide Overwrite existing files Option in Upload Document Page of SharePoint 2010.
hide overwrite existing files option in sharepoint 2010

Solution:
If the "Overwrite existing files" option to be turned off for all uploads, You can Locate these lines and Change the Checked="true" to Checked="false" in Uploadex.aspx file as below:
  1. <asp:CheckBox id="OverwriteSingle" Checked="true" Text=<%$Resources:wss,upload_document_Overwrite_file%>" runat="server" />
  2. <asp:CheckBox id="OverwriteMultiple" Checked="true" Text=<%$Resources:wss,upload_document_Overwrite_version%>" runat="server" />
Alternatively, Lets set this option only for specific site. 
  • Login to your SharePoint Web Front End Server, Navigate to: "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\template\layouts" folder
  • Make a backup of "Uploadex.aspx" file and open it in Notepad.
  • Search for text </asp:Content> from the top and Insert the below code in it.
  • <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
     $(document).ready( function () {
     if(location.href.indexOf('globalfunctions/credit/_layouts/Upload.aspx') >= 0) {
    
                $("input[id$='OverwriteSingle']").removeAttr('checked');
                $("input[id$='OverwriteSingle']").hide();
                $("label[for$='OverwriteSingle']").hide();
                $("a[id$='UploadMultipleLink']").hide();
    
          }
     });   
    </script>
    
  • Save and close the uploadex.aspx file. Repeat these steps in all your web front end servers if you have more than one.
My requirement is to hide overwrite existing files and upload multiple files options for only a particular subsite, so I've wrapped the code inside "IF" condition. Here is the Result of hidden overwrite existing files option and multiple upload link in upload page:
hide upload multiple files

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


Monday, February 23, 2015

Fix People Picker is Very Slow in SharePoint 2010

Problem: In a SharePoint 2010 environment, People picker is very slow! It takes more than 30 seconds to resolve any given users names in person or group fields.
sharepoint 2010 people picker is too slow
SharePoint 2010 People Picker is too slow resolving
Solution:
Instruct people picker to search only within given AD domains! Here is how:

Set People Picker SearchADForest domains:
stsadm -o setproperty -pn peoplepicker-searchadforests -pv "domain:crescent.com" -url "https://portal.crescent.com"

If you have multiple domains, add ; as separators in PV parameter. E.g. "domain:Apac.crescent.com;domain:crescent.com" in 2 way trusted domains.

To get People Picker SearchADForest value applied:
Stsadm -o getproperty -pn peoplepicker-searchadforests -url "https://portal.crescent.com/"

To Clear People Picker SearchADForest values if exist already:
Stsadm -o getproperty -pn peoplepicker-searchadforests -pv "" -url "https://portal.crescent.com/"

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


Saturday, February 21, 2015

Fix "Value does not fall within the expected range" Error in SharePoint

Problem: SharePoint site gave "System.ArgumentException: Value does not fall within the expected range" error!

Here are some possible root causes and solutions
Case 1: While fetching List item Lookup values programmatically
Root cause: List view threshold value Exceeded! This occurs due to throttling limit on list view lookup threshold value under web application settings. Try increasing it.
  • Go to Central Administration >> Application Management >> Manage web applications
  • Select your web application, Click on General Settings >> Resource Throttling from the ribbon
  • Enter the value for List View Lookup Threshold. E.g. 36
    Fix "Value does not fall within the expected range" Error in SharePoint
PowerShell script to increase list view lookup threshold value.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$WebApp = Get-SPWebApplication "http://sharepoint.crescent.com/"

#Set List View Lookup Threshold  
$WebApp.MaxQueryLookupFields = 36
$WebApp.Update()

Case 2: Invalid Field Names
When fetching fields, use internal field names or check whether the particular field exists before trying to get its value. E.g. Use item.Fields.ContainsField("Title") before fetching or updating a specific field. So, if you got this error after activating a feature or deploying a solution, culprit is your recent feature/solution!

Case 3: During Check-In under SharePoint Document Library:
Got this error while checking in a document ? Well, the solution is simple - Do not set required field property to true on your content types!

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


Friday, February 20, 2015

New-SPLogFile PowerShell Cmdlet in SharePoint Troubleshooting

New-SPLogFile cmdlet in SharePoint 2013 creates new ULS trace log file on execution. In other words, once you execute this New-SPLogFile command, it ends the current log file and creates a new log file. All subsequent errors will be placed in the new log file, which intern greatly helps to isolate all new errors.

Its a good idea to start a new log file when you troubleshoot any issues in SharePoint as identifying current issue from existing logs could be cumbersome while existing log files can become large and difficult to scan through. Here is how you can utilize New-SPLogFile cmdlet.
  • Go to SharePoint PowerShell Management Shell
  • Type: New-SPLogFile and hit enter. It doesn't has any parameters.  
  • Now, your new trace log file will be created. Once the new log file is created, you can trigger the event that is causing issues.
    New-SPLogFile PowerShell command
  • Get your trace log location from diagnostic log path. Go to: Central Administration >> Monitoring >> Configure diagnostic logging >> Trace Log Path 
    powershell new-splogfile sharepoint
  • Go to the trace log location, sort using created date, and there you'll find your new log file created! Open it to start your troubleshooting.
Technet referece on New-SPLogFile


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


Thursday, February 19, 2015

Redirect from HTTP to HTTPS in SharePoint using IIS URL Rewrite Module

How to redirect http to https in SharePoint 2013:
Changing SharePoint site from http to https is a common requirement. URL Rewrite module is a great plugin for IIS to achieve various sort of redirects in your SharePoint site (or any web site technically!). Lets see how to implement HTTP to HTTPS redirect with IIS URL Rewrite Module.
Assuming you have SSL certificate for your website imported in IIS and 443 Binding is added. Also you have AAM Entry for HTTPS!

Prerequisites: Download and Install URL Rewrite module
As a prerequisite, you need to have URL rewrite module added to your web server. If its already installed in your web server , you'll find "URL Rewrite" module icon as below.
convert http to https sharepoint 2013

If its not installed already, Go to https://www.iis.net/downloads/microsoft/url-rewrite download and install URL rewrite module. Lets configure URL redirect to change SharePoint site from http to https.
change sharepoint site from http to https
Configure HTTP to HTTPS Redirect using URL Rewrite
  • Open IIS >> Select your web site from Sites node >> Open URL Rewrite module. 
  • Click on "Add Rules" link in the Actions menu and then select "Blank" inbound rule template. 
     sharepoint 2013 redirect from http to https
  • Provide a Name to the Rule. Say: "Redirect HTTP to HTTPS". Under "Match URL" Section: Set
    how to redirect http to https sharepoint 2013
    • Requested URL: Matches the Pattern
    • Using: Regular Expressions
    • Pattern: (.*)
  • Under "Conditions", Click on "Add" button to add a new condition
    how to change http to https in sharepoint
    • Condition Input: {HTTPS}
    • Check if input string: Matches the Pattern
    • Pattern: ^OFF$
      redirect http to https in sharepoint 2013
  • In Action Type Section, Set the following:
    sharepoint 2013 http to https url rewrite
    • Action Type: Redirect
      Redirect URL: https://{HTTP_HOST}/{R:1}
      Redirect Type: Permanent (301)
  • Click "Apply" from actions panel to save your changes!That's all. This converts http to https in SharePoint 2013.

These changes creates below entries in web.config file of the website.
      <rewrite>
            <rules>
                <rule name="Redirect HTTP to HTTPS" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="^OFF$" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" />
                </rule>
            </rules>
        </rewrite>
Now, when a user hits any HTTP link on your site, the URL rewrite module redirects them to HTTPS of the same link!

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


Wednesday, February 18, 2015

How to Hide Share, Follow and Sync Buttons in Sharepoint 2013

We got a requirement to remove Share, Follow and Sync buttons in SharePoint 2013. Let me summarize various ways to disable these buttons.
sharepoint 2013 disable share, follow, sync buttons
How to disable "Share" button in SharePoint 2013?
Share button is relying on "Access requests" configuration of the site. To disable "Share button" in SharePoint 2013, simply disable access requests.
  • Go to Site settings page of your SharePoint site.
  • Click on "Site Permissions" link under "Users and Permissions" group
  • Click on "Access Request Settings" in the ribbon.
  • Uncheck "Allow access request" and click on "Ok" to save your changes. This should hide Share button in SharePoint 2013.sharepoint 2013 disable share button
Remember, You will have to do this change for each site! However, Share button will still be visible for Site owners and administrators!

How to Disable Sync buttons in SharePoint 2013
To disable sync, Navigate to  Site settings >> Click on "Search and offline availability" >> set offline client availability to "No". There are few more ways discussed in my another article: Hide Sync Button in SharePoint 2013

How to disable "Follow" button in SharePoint 2013?
To disable "Follow" button in SharePoint 2013, You'll have to disable a feature called "Following Content". Navigate to:
  • Site Settings >> Click on "Manage Site Features"
  • Click on "Deactivate" on " Following Content" feature
This removes following button in SharePoint 2013. If you want to disable "Following" feature at Farm level, disable "ContentFollowingStapling" hidden feature at Farm Level:
Disable-SPFeature -identity "ContentFollowingStapling"

Disable Access Request, Deactivate Features using PowerShell:

  • Share: To disable access requests on all sites using PowerShell, refer: Disable access request in SharePoint 2013
  • Following: To deactivate "Following content" feature using PowerShell as:
    Disable-SPFeature -identity "FollowingContent" -URL "http://your-sp-site.com/" 
  • Sync: To exclude from offline client, run:
    Get-SPSite -limit all | get-SPWeb -limit all | Foreach { $_.ExcludeFromOfflineClient=1; $_.Update()} 

Remove Share, Follow, Sync buttons at Master page level:

These promoted action buttons are in master page as follows:
Share Button:
Follow Button:
<SharePoint:DelegateControl ID="DelegateControl2" runat="server" ControlId="PromotedActions" AllowMultipleControls="true" />
Sync Button:
<SharePoint:SPSyncPromotedActionButton ID="SPSyncPromotedActionButton1" runat="server" />
To hide these controls, simply move them inside Comment block. <!--  -->. Do not delete this controls from the Master page! You'll end-up in crash!!

CSS to hide Share, Follow and Sync Buttons:

Lets hide them based on their IDs. You can place this CSS code with "Script Editor" web part or you can place it in Master page.
  • Sync button's id: ctl00_SyncPromotedAction
  • Follow button id: site_follow_button
  • Share button's id:  ctl00_site_share_button
<style type="text/css">

a[id$=site_share_button], a[id$=SyncPromotedAction], a#site_follow_button
{
    display: none !important;
} 

</style>
Tips: This hides Share button from promoted actions section. But share button is present in ECB/Callout menu and in list view quick control also. To hide them all as well, use selectors:  a[id$="site_share_button"], a.ms-calloutLink[title="Share"], button.js-listview-qcbShareButton.

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


Tuesday, February 17, 2015

Find Installed SharePoint Product Edition using PowerShell

To determine SharePoint edition installed , use this PowerShell script:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Hashtable to define Installed product from its GUID
#Based on: https://msdn.microsoft.com/en-us/library/office/jj659075.aspx and
#https://msdn.microsoft.com/en-us/library/ff721969.aspx

    $SharePointProducts = @{
                "BEED1F75-C398-4447-AEF1-E66E1F0DF91E" = "SharePoint Foundation 2010"
                "1328E89E-7EC8-4F7E-809E-7E945796E511" = "Search Server Express 2010"
                "B2C0B444-3914-4ACB-A0B8-7CF50A8F7AA0" = "SharePoint Server 2010 Standard Trial"
                "3FDFBCC8-B3E4-4482-91FA-122C6432805C" = "SharePoint Server 2010 Standard"
                "88BED06D-8C6B-4E62-AB01-546D6005FE97" = "SharePoint Server 2010 Enterprise Trial"
                "D5595F62-449B-4061-B0B2-0CBAD410BB51" = "SharePoint Server 2010 Enterprise"
                "BC4C1C97-9013-4033-A0DD-9DC9E6D6C887" = "Search Server 2010 Trial"
                "08460AA2-A176-442C-BDCA-26928704D80B" = "Search Server 2010" 
                "84902853-59F6-4B20-BC7C-DE4F419FEFAD" = "Project Server 2010 Trial"
                "ED21638F-97FF-4A65-AD9B-6889B93065E2" = "Project Server 2010"
                "926E4E17-087B-47D1-8BD7-91A394BC6196" = "Office Web Companions 2010"
                "35466B1A-B17B-4DFB-A703-F74E2A1F5F5E" = "Project Server 2013"
                "BC7BAF08-4D97-462C-8411-341052402E71" = "Project Server 2013 Preview"
                "C5D855EE-F32B-4A1C-97A8-F0A28CE02F9C" = "SharePoint Server 2013"
                "CBF97833-C73A-4BAF-9ED3-D47B3CFF51BE" = "SharePoint Server 2013 Preview"
                "B7D84C2B-0754-49E4-B7BE-7EE321DCE0A9" = "SharePoint Server 2013 Enterprise"
                "298A586A-E3C1-42F0-AFE0-4BCFDC2E7CD0" = "SharePoint Server 2013 Enterprise Preview"
                "D6B57A0D-AE69-4A3E-B031-1F993EE52EDC" = "Microsoft Office Web Apps Server 2013"
                "9FF54EBC-8C12-47D7-854F-3865D4BE8118" = "SharePoint Foundation 2013"
                  }    

#Get currently installed product's GUID
$InstalledProducts =  (Get-SPFarm).Products

#Determine the product edition based on GUID from the HASH Table
$InstalledProducts | ForEach-Object { write-host $SharePointProducts.Get_Item($_.GUID) }

Please note, You'll always get "SharePoint Foundation" as installed product along with all other SharePoint products such as "SharePoint Server 2013 Enterprise".  Also, Office Web Apps doesn't work as its installed separately from SharePoint server farm.

Related posts:
Tags: sharepoint edition check, how to find sharepoint 2013 edition, how to determine sharepoint 2013 edition, how to know sharepoint 2010 edition, sharepoint 2010 get edition, sharepoint powershell get edition, determine sharepoint edition installed

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


Monday, February 16, 2015

How to Rename SharePoint 2013 Content Databases with PowerShell

Requirement: To follow standard naming conventions, We got to rename SharePoint content databases in our SharePoint 2013 environment.

Solution:
You can rename a SharePoint content database in these three steps as explained in my another post: How to Rename SharePoint 2013/2010 Central Admin Database and Remove GUID
  1. Detach SharePoint content database from SharePoint web application
  2. Rename the content database in SQL Server
  3. Attach the renamed content database back to SharePoint
rename sharepoint content database powershell

With the help of PowerShell, Lets automate these manual steps.

Rename SharePoint content database with PowerShell:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Load the assemblies required for the SQL database rename.
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") 
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO")
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended")

#Function to Rename Database in SQL Server
function Rename-SQLDatabase($DBServerName, $OldDatabaseName, $NewDatabaseName)
{
    try
    {
        Write-host Establishing connection with SQL Server... -foregroundcolor "Yellow"
        #Connect to the server
        $Server = new-Object Microsoft.SqlServer.Management.Smo.Server($DBServerName)
        
        Write-host Getting the Database in SQL Server... -foregroundcolor "Yellow"
        #Get the database
        $Database = $Server.Databases.Item($OldDatabaseName)

        #Kill all active connections to the SQL database
        $Server.KillAllprocesses($OldDatabaseName)

        Write-host Renaming  Database in SQL Server... -foregroundcolor "Yellow"
        #Rename the database
        $Database.Rename($NewDatabaseName)
        Write-host Database Renamed from $OldDatabaseName to $NewDatabaseName in SQL Server -ForegroundColor Green
    }

    catch
    {
        Write-Error $_.Exception.Message
        Write-Error "Error in Renaming Database in SQL Server!" 
    }
}

#Function to Rename content database in SharePoint
function Rename-ContentDatabase($OldDBName, $NewDBName)
{
    try
    {
        Write-host Getting SharePoint Content Database ... -foregroundcolor "Yellow"
        $ContentDB = Get-SPContentDatabase | Where-object {$_.Name -eq $OldDBName}

        #Get Content Database settings
        $WebApp = $ContentDB.WebApplication.Url
        $DBServer = $ContentDB.Server
        $MaximumSites = $ContentDB.MaximumSiteCount
        $WarningSites = $ContentDB.WarningSiteCount

        #Dismount Content Database
        Write-host Dismounting Content Database ... -foregroundcolor "Yellow"
        Dismount-SPContentDatabase $OldDBName -Confirm:$False

 
        Write-host Renaming Database: $OldDBName to $NewDBName in SQL Server -foregroundcolor "Yellow"

        #Call function to rename Database in SQL Server 
        Rename-SQLDatabase $DBServer $OldDBName $NewDBName

        Write-host Mounting SharePoint content Database... -foregroundcolor "Yellow"
        #Mount the database back
        Mount-SPContentDatabase -Name $NewDBName -WebApplication $WebApp -DatabaseServer $DBServer -MaxSiteCount $MaximumSites -WarningSiteCount $WarningSites | out-null

        Write-host Done!Content Database Renamed from $OldDBName to $NewDBName!! -ForegroundColor Green
    }
     catch
    {

        Write-Error $_.Exception.Message
    }
}

#Call the function to rename database
Rename-ContentDatabase "WSS_Content_310d122490c4303b1c0b3f2f695e7" "HostingFarm_Content_Hosting01" 




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


Sunday, February 15, 2015

How to Limit NodeRunner.exe High Memory, CPU Usage?

Problem: NodeRunner.exe is consuming a lot of memory and CPU resulted in performance issues on SharePoint 2013 server.

Solution:
NodeRunner.exe is a SharePoint 2013 Search service component and it is resource hungry. To reduce the CPU and Memory impact of this process, follow below steps:

Step 1: Reduce the CPU impact of the search service
By default SharePoint search uses "maximum" to speed up its search crawling process. To reduce the CPU usage of the search service, run this PowerShell script from any one of your SharePoint 2013 server:
Set-SPEnterpriseSearchService -PerformanceLevel Reduced
This sets Search Service Application crawl component to use less number of threads.

Step 2: Limit the NodeRunner.exe's Memory usage:
  • Open the configuration file at "C:\Program Files\Microsoft Office Servers\15.0\Search\Runtime\1.0\noderunner.exe.config" 
  • Locate the node "nodeRunnerSettings", Set the value for "memoryLimitMegabytes" attribute to specific value (E.g. 1024). By default its value is 0 (which means unlimited memory). 
    sharepoint 2013 noderunner memory limit
Step 3: Restart Search Service
For the above steps to take effect, You have to restart SharePoint 2013 search service. Go to Services console, restart SharePoint Search Host Controller process. Or use the PowerShell cmdlet to restart Search host controller process:
Restart-Service SPSearchHostController

The downside of the above changes: Since you are restricting resources to SharePoint search service, it increases search crawl time!

Do not limit node runner memory in Production Servers!Instead try increasing the Memory on SharePoint Production servers.

Tags: noderunner.exe high cpu sharepoint 2013, noderunner exe sharepoint 2013 high cpu, noderunner.exe sharepoint 2013 high memory, sharepoint noderunner memory limit, noderunner.exe high memory sharepoint 2013, noderunner.exe sharepoint 2013 search, sharepoint noderunner reduced, sharepoint noderunner memory usage

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


Friday, February 13, 2015

SharePoint Online: PowerShell to Delete Site Collection

How to delete a SharePoint Online Site collection using PowerShell?
Import-Module Microsoft.Online.Sharepoint.PowerShell

#Variables for processing
$AdminSiteURL = "https://crescent-admin.sharepoint.com/"
$AdminName = "salaudeen@crescent.onmicrosoft.com"
$SiteCollURL = "https://crescent.sharepoint.com/sites/Sales"

#Credentials to connect 
$SecurePWD = ConvertTo-SecureString "Password" –asplaintext –force  
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $AdminName, $SecurePWD
 
#Connect to SharePoint Online
Connect-SPOService -url $AdminSiteURL -credential $Credential

#Delete SharePoint Online Site Collection
Remove-SPOSite -Identity $SiteCollURL -NoWait -Confirm:$false

Write-Host "Site collection has been deleted!"

Permanently Delete the SharePoint Online Site Collection:
When you delete a site collection, it goes to recycle bin. You may want to permanently delete that site collection to reuse the storage space or recreate a new site collection with the same URL.
SharePoint Online PowerShell to Delete Site Collection
#Remove Deleted SharePoint Online Site Collection permanently
Remove-SPODeletedSite –identity $DeletedSiteCollURL -Confirm:$false


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


Thursday, February 12, 2015

Configuration Failed: Failed to create the configuration database in SharePoint Products Configuration Wizard

Problem:
Experiencing "Configuration Failed" error message while running SharePoint SharePoint 2013 Products Configuration Wizard right after new installation/patching. It got stuck while performing configuration task 3 of 10. Creating the configuration database...

Which ended with an error message:
"Configuration Failed: 
Failed to create the configuration database.
An exception of type System.Security.Principal.IdentityNotMappedException was thrown. Additional exception information: Some or all identity references could not be translated."
Configuration Failed: Failed to create the configuration database in SharePoint Products Configuration Wizard
Solutions:
  • Make sure SQL Server is running on a service account which is granted with local administrator access rights! (Not running on accounts such as: local service, network service!)
    If so, update the Log On account of SQL Server Service in your database server.
  • Check TCP/IP and Named Pipes protocols are enabled in SQL Server. 
  • Check your Firewall. Turn it off for time being. Check your event logs for any antivirus related blocks.  
  • Make sure your setup account (or the account you are currently logged in and running the SharePoint Products Configuration Wizard) is granted with : dbcreator, securityadmin and sysadmin access rights in SQL Server.
  • Check the application pool identity for "SharePoint central administration" site! It should be your Farm account and not  "network service"
  • Do not use your service account username has with more than 20 characters (SharePoint uses the pre-windows 2000 username)
  • If all fails, Run PSConfig command line, and then Try running the Products configuration Wizard GUI again!
    psconfig -cmd configdb <-create/connect> -server <db-servername> -database <database name> -user <service-account-username> -password <password> -admincontentdatabase <content database name>
  • Delete the config database in Database Server. Delete the Central admin site and App Pool in IIS. and try running the wizard again.
Run the SharePoint Configuration wizard again, after fixing with the above workarounds.

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


Tuesday, February 10, 2015

Create a Document Library in SharePoint using PowerShell

Requirement:
Create a document library in SharePoint 2013 using PowerShell.

PowerShell Script to Create New Document Library in SharePoint:
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

#PowerShell Fuction to Create a Document library in SharePoint 
Function Create-DocumentLibrary
{
 Param
 ( 
  [Microsoft.SharePoint.SPWeb]$Web,
  [String] $LibraryName,
  [String] $Description
 )
    #Get the Document Library template
    $ListTemplate = [Microsoft.Sharepoint.SPListTemplateType]::DocumentLibrary
  
    #Check if the library already exists
    if(($web.Lists.TryGetList($LibraryName)) -eq $null)
    {
        #Create the Library
        $Web.Lists.Add($LibraryName,$Description,$ListTemplate) > Null
   
        #Set Properties of Library such as OnQuickLaunch, etc
        $Library =  $Web.Lists[$LibraryName] 
        $Library.OnQuickLaunch = $true
        $Library.Update()
   
        Write-Host "Document library created successfully!" -f Green
    }
    else
    {
        Write-Host "Document Library '$LibraryName' already exists!" -f Red
    }
}
 
#Get the Web
$web = Get-SPWeb "http://intranet.crescent.com/"
 
#Call the function to create library
Create-DocumentLibrary $web "Team Forms" "Library to Share Team Documents"
 


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


Sunday, February 8, 2015

SharePoint Datasheet Error: An Error 0x80070057 Occurred. No further information was provided

In People picker field in SharePoint 2010 datasheet view, on entering new values got this error message: An Error 0x80070057 Occurred. No further information was provided.
An Error 0x80070057 Occurred. No further information was provided

Moreover, People picker field drop down was empty!

Fix:
  1. Open your list in SharePoint designer
  2. Edit list columns >> Make some dummy modification to the "Person or Group" column which is causing the problem.
  3. Hit save button in SharePoint Designer once done.


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


Open a Page in Popup Modal Dialog Window in SharePoint 2013

Requirement: Open a page in Modal Popup window in a SharePoint 2013 web site.
JavaScript to open popup in sharepoint 2013

Solution:
Requirement is to open "Terms and Conditions" page in popup window on clicking the link. Used this HTML code to open a page in modal popup window in SharePoint 2013:
<a href="#" onclick="OpenPopUpPageWithTitle('http://crescent.com/sitepages/terms.aspx', null, 600, 600,'Terms & Conditions')"/> Terms and Conditions </a>
and here is the result:
SharePoint 2013 open page in popup

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


Create SharePoint Group from Active Directory Group

Requirement: Convert Active Directory Group into SharePoint Group!

Solution: Managing SharePoint users at Active Directory Security group and within SharePoint has its own advantages and disadvantages too. Now, our requirement is to migrate from AD group to SharePoint group. So, Lets use PowerShell to create new SharePoint group from Active directory security group. Here is my script:

Create SharePoint group from active directory group:
#Import Active directory & SharePoint PowerShell modules
Import-Module ActiveDirectory
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
  
#Variables for processing
$SiteURL="http://Intranet.crescent.com/"
$ADGroupName="SP13 Authors"
$SPGroupName="Content Authors"
$PermissionLevel="Full Control" #Permission to SPGroup
$Domain="Crescent" #AD Domain

#Get the Site collection's Root Web
$web = Get-SPWeb $SiteURL

#Check if Group Exists already
 if ($web.SiteGroups[$SPGroupName] -ne $null)  
 {  
  write-Host "Group Name Already in the site!!" -ForegroundColor Red 
 }  
 else  
 {  
  #Create New SharePoint Group
  $SPGroup = $web.SiteGroups.Add($SPGroupName, $web.Site.Owner, $web.Site.Owner, $null)
  #Get the newly created group and assign permission to it
  $SPGroup = $web.SiteGroups[$SPGroupName]  
  $RoleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($SPGroup)  
  $RoleDefinition = $web.RoleDefinitions[$PermissionLevel]  
  $RoleAssignment.RoleDefinitionBindings.Add($RoleDefinition)  
  $web.RoleAssignments.Add($RoleAssignment)  
  $web.Update()  
  Write-Host "New Group $SPGroupName has been created!" 
 
  #Get Members of AD Group
  $ADGroupMembers = Get-ADGroupMember -Identity $ADGroupName | Select-Object -ExpandProperty SamAccountName    
  Write-host "Total Users Found in the AD Group:"$ADGroupMembers.Count

  #Add Members to SPGroup from ADGroup
  $ADGroupMembers | ForEach-Object {
   #Convert to Domain\User format
   $UserID =  "$Domain\$_" 
   #Get Claims ID. E.g. Domain\User to i:0#.w|Domain\User
          $UserClaimsID = (New-SPClaimsPrincipal -identity $UserID -IdentityType "WindowsSamAccountName").ToEncodedString() 
          $SPGroup.Users.Add($UserClaimsID,"", "", "") 
   Write-host "User Added from AD Group to SharePoint Group:" $UserClaimsID
  }  
 }

Active Directory PowerShell Module:
You need to have "Active Directory module for Windows PowerShell" in Windows Server 2008/2012 member servers. Use this PowerShell cmdlet to add this feature:
Add-WindowsFeature RSAT-AD-PowerShell 
Alternatively, you can Go to: Server Manager >> Add Roles and Features >> Choose "Active Directory Module for Windows PowerShell" under Remote Server Administration Tools.
create sharepoint group from active directory group


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


Friday, February 6, 2015

How to Disable Minimal Download Strategy (MDS) in SharePoint 2013

SharePoint 2013 introduced a new concept called Minimal download strategy to minimize the amount of data downloaded from your SharePoint site to client and making it load faster. For example when we navigate from a site's home page to Shared Documents page, MDS downloads only the content that has changed between the source and destination pages. The feature is scoped at site level (SPWeb) and activated by default in certain site templates such as team sites, community sites, blog, projects, wiki etc. (not available with publishing sites).

When MDS is activated, you will find in the page URL /_layouts/15/start.aspx followed by a hash(#) and then the relative url of the site you requested.
E.g. http://www.crescent.com/sales/_layouts/15/start.aspx#/SitePages/home.aspx 

Deactivating this feature will no longer redirect all of the URLS to include the /_layouts/15/start.aspx# path in your address, keeping everything nice and tidy. E.g. http://www.crescent.com/sales/SitePages/home.aspx

Why to Disable Minimal Download Strategy Feature?
Of course, MDS has both pros and cons. In my experience, we had to disable MDS on below scenarios:
  • When we deployed a custom JavaScript file in our SharePoint site, MDS caused errors in page rendering!
  •  OWSSRV.dll 65000 - Cannot complete this action Error: We experienced this error when the page is trying to make a Remote Procedure Call (RPC) to owssvr.dll during Deleting a List, Modifying List View, etc.
  • When we used TMG as our secure proxy server, we found that the MDS feature consistently caused errors while loading pages.
  • "Connect to Outlook" is greyed out and you’re unable to connect a document library to Outlook.
  • Random access denied, 401 Unauthorized Errors.
We found disabling MDS feature resolved all of the above errors!

How to deactivate minimal download strategy in SharePoint 2013:
So, You have decided to disable minimal download strategy feature! Follow these steps to turn off minimal download strategy.
  • Browse to the Site Settings page of your SharePoint 2013 site.
  • Click on Manage site features under Site Actions
  • Locate and Click on Deactivate button next to "Minimal Download Strategy" feature
    minimal download strategy in sharepoint 2013 disable
  • Confirm disable minimal download strategy by clicking on "Deactivate this feature" link.
    minimal download strategy in sharepoint 2013 disable
  • You have to deactivate in all sites in your site collection/web application to disable MDS in SharePoint 2013 completely. Repeat these steps, click on "Activate" button instead of deactivate if you want to enable it back!
This removes "_layouts/15/start.aspx#" in SharePoint URL address bar!

Drawback: Enabling or disabling of MDS feature should be performed on site by site basis. So, Lets seek help from PowerShell to avoid this time consuming task.

Disable MDS in SharePoint 2013 using PowerShell
To disable Minimal Download Strategy for a given web, use this PowerShell script:
#SharePoint site URL
$WebURL ="http://teamsites.crescent.com/support/" 

#To dectivate MDS feature 
Disable-SPFeature –identity "MDSFeature" -URL $WebURL -confirm:$false

#To Enable MDS feature 
#Enable-SPFeature –identity "MDSFeature" -URL $WebURL -confirm:$false
Internally, when disabled or enabled, it sets the EnableMinimalDownload property of the SPWeb object.

SharePoint 2013 minimal download strategy - Disable for entire web application:
At times you may need to enable/disable the MDS feature on all sites in your web application. We have got a web application with 500+ site collections and multiple sites. Not wise to choose SharePoint web UI way, but you can achieve this smartly by using below PowerShell script:
Add-PSSnapin Microsoft.SharePoint.PowerShell –ErrorAction SilentlyContinue

#SharePoint web App URL
$WebAppURL ="http://teamsites.crescent.com" 
$FeatureName ="MDSFeature"

#disable the MDS for all web applications
$WebsCollection = Get-SPWebApplication $WebAppURL | Get-SPSite -Limit All | Get-SPWeb -Limit All

foreach($web in $WebsCollection)
{
    #Check if the feature is activated 
    $MDSFeature = Get-SPFeature -web $Web.Url  | Where-object {$_.DisplayName -eq $FeatureName}
  
    if($MDSFeature -ne $null)
    {
        Disable-SPFeature –identity $FeatureName -URL $web.URL -confirm:$false
        write-host "Minimal Download Strategy Feature has been disabled at: "$web.Url
    } 
}

Disable the "Minimal Download Strategy" feature at the farm level: 
You can deactivate the "Minimal Download Strategy" feature at the farm level so that it is disabled by default on any new site collections and sites which are created.
# Uninstall Feature
Uninstall-SPFeature MDSFeature -Force -Confirm:$false

# To Re-Install Feature to enable it
# Install-SPFeature MDSFeature


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


Thursday, February 5, 2015

Word cannot register your account. The provider where you are trying to publish is unavailable. Contact your provider for assistance.

Problem:
Tried publishing a blog post to SharePoint blog from Microsoft Word 2013 from "File >> Share >> Publish to Blog". While registering a new SharePoint blogging account, got this error message "Word cannot register your account. The provider where you are trying to publish is unavailable. Contact your provider for assistance."
Solution: 
Go to SharePoint 2013 Central Administration >> Manage Web Applications >>Web Application General Settings >> Set the option for "Allow user name and password from the API" to Yes.
Another cause and solution:
If your current logged in Windows user account isn't the same as your SharePoint account, You may get this error! Set your Internet Explorer's settings to prompt of user name and password. Delete your cookies and try again. You should get this "Account registration successful" message.


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


Sunday, February 1, 2015

Application Pool Monitoring for SharePoint using PowerShell Script

If SharePoint Application Pools are stopped that would cause "Service Unavailable" outages to your SharePoint environment! While SCOM can monitor SharePoint IIS web application's application pool status, it makes bit more noisy with alerts and doesn't start the application pool automatically - when stopped. So, lets address this issue with the help of PowerShell! Here is my nifty PowerShell script to monitor application pools on all SharePoint web front end servers.

This script not only scans IIS Application Pool status on SharePoint Web-Front end servers, But also:
  • Logs application Pool status if its not in Started state
  • Automatically starts AppPool if its in stopped state
  • Sends out an Alert-Email to SharePoint Admin team (or whoever configured!)
PowerShell script to Monitor IIS Application Pool statues:
Import-Module WebAdministration

#Array to hold Server names - Change it to YOUR SharePoint front end servers
$WFEServers =("HS-WFE01", "HS-WFE02", "HS-WFE03")

#Log file location
$LogFile = "D:\Scripts\AppPool-Log.txt"

#Loop through each server and Check Application Pool status
foreach ($Server in $WFEServers)
{
    $ServerMgr = [Microsoft.Web.Administration.ServerManager]::OpenRemote($Server)

    #Get all Application Pools which are not in Started State
    $AppPoolColl = $ServerMgr.ApplicationPools | Where-Object {$_.State -ne "Started"}

    foreach($AppPool in $AppPoolColl)
    {
        #Get the time to Log
        $now = Get-Date –f "yyyy-MM-dd HH:mm:ss"

        #Log to file
        "`n Found Application Pool: $($AppPool.name) in stopped state at the server : $($Server) on $($now)" >> $LogFile
        "Trying to Start the application Pool...">> $LogFile
        
        #Try Starting the application Pool
        $AppPool.Start()
        Start-Sleep -s 10
        "Application Pool's current Status: $($AppPool.State)" >> $LogFile

        #Send Alert-Mail message
        $emailFrom = "AppPoolMonitor@crescent.com"
        # Use commas for multiple addresses
        $emailTo = "SPAdmins@crescent.com"
        $subject = "Application Pool: $($AppPool.Name) in stopped state in Server: $($Server) at $($now)"
        $body = "Hi SharePoint Team, `n `n The Application Pool $($AppPool.name) was in stopped state in server: $($server). `n`n We tried Re-starting it... Current State of the Application Pool: $($AppPool.State). `n`n Please take necessary actions if its not started !. `n `nThanks, `nSharePoint AppPool Monitoring Script."
        $smtpServer = "smtp.crescent.com" #IP or HOST Name of SMTP Server
        $smtp = new-object Net.Mail.SmtpClient($smtpServer)
        $smtp.Send($emailFrom, $emailTo, $subject, $body) 
    } 
}
Here is the sample alert from IIS AppPool monitoring script:

Schedule this PowerShell script in Windows Task scheduler in any Application server (or any other server will do!) to periodically scan App Pool status, Say once per 5 Min! run interval can be adjusted based on your application priority.

Here is my another post on Scheduling PowerShell scripts using Windows Task scheduler: Create a Scheduled Task for PowerShell Script with Windows Task Scheduler

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...