Wednesday, August 27, 2014

How to Create Default Groups in SharePoint Site

Problem: The default SharePoint groups are created automatically when you create a site collection through SharePoint Web UI. But, when you Create SharePoint sites programmatically or with PowerShell, The default site groups (Such as: Visitors, Members, Owners) are not created automatically

Default groups creation from UI: You can get the default group page from SharePoint UI by navigating to :  http://your-sharepoint-site.com/_layouts/permsetup.aspx . Enter group details and hit "Save".
How to Create Default Site Groups in SharePoint
How to create default SharePoint groups:
You have to call the method: SPWeb.CreateDefaultAssociatedGroups explicitly. to create default user groups in SharePoint.

Create Default User Groups programmatically using PowerShell:
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

#Variables for Site collection
$SiteURL ="https://intranet.crescent.com"
$Site = Get-SPSite $SiteURL

#get the Root Web object
$RootWeb = $Site.RootWeb

$GroupOwner = "i:0#.w|global\salaudeen" 
$RootWeb.CreateDefaultAssociatedGroups($GroupOwner, "", $RootWeb.title)


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


Tuesday, August 26, 2014

Installing and Configuring ADFS Integration with SharePoint 2013 - Step by Step Guide

Introduction:
Active directory federation services is the solution for extending enterprise identity beyond corporate firewall. It simplifies sharing identities between trusted partners across organizations. Its a common requirement in a typical business scenario, users in one organization wants to access a secured application/website from an another organization. Without ADFS, we'd end-up re-creating user logins for the partner company in our AD. But that introduces the problem of maintaining and managing two separate identities for the partner company users. Here is where ADFS comes to the picture. It solves the problem by federating identities and establishing single sign-on capability. SharePoint 2013 - ADFS integration is seamless as its natively supported.

Generally, in SharePoint world, ADFS is used in these three scenarios:
  1. Domains which are not part of your AD forest  (Such as acquired companies without trusts established, with network connectivity between them in place): User in one organization accesses an application in another organization, so that you can collaborate across organizational boundaries. Say for E.g. Your company is running an internal SharePoint site/application and your partner company/acquired company wants to make use of the same.  across organizational boundaries without duplicating user logins.
  2. Extranet setups for partners/customers - Accessing SharePoint application via the Internet, which extends the first scenario to include remote Internet access who are outside the organization. The external domain is still responsible for validate provided credentials and pass it on the SharePoint.
  3. Office 365/Cloud - You are running a SharePoint farm either in Cloud or in Office 365 and want to provide access to the users of your company without re-creating their identities in the cloud.
How the ADFS - SharePoint authentication process works?
  • User types SharePoint site URL and picks the relevant authentication provider from the sign-in page
  • SharePoint redirects to the respective ADFS server configured already, User promoted for credentials.
  • ADFS handles the authentication by Verifying the provided user name and password from the identity provider - AD
  • ADFS creates a Token, Signs and puts it in a cookie. Redirects to SharePoint with that cookie
  • SharePoint STS validates and extracts the claims from the token
  • SharePoint performs authorization and connects the user to the web application.

There are Three steps involved in integrating ADFS with SharePoint 2013:
  1. Install ADFS Server
  2. Create a trusted relying party for SharePoint 2013 in ADFS
  3. Configure SharePoint 2013 to trust ADFS

Prerequisites:
There are certain prerequisites to be addressed for ADFS SharePoint 2013 configuration.
  1. SSL Certificates: Obtain SSL certificates for your SharePoint 2013 web application, and at least two certificates for ADFS Service communication and for ADFS token signing of 2048-bits.
  2. Default Web Site in IIS - Make sure, in your ADFS Server, the default web site is running in IIS. This site to be SSL enabled with ADFS communication certificate.
  3. SharePoint Web Application requirements: Your web app must be SSL enabled and  authentication mode must be "Claims Based" - which is default in SharePoint 2013. Security Token Service must be up and running.
  4. DNS Entries: Make sure DNS entries (or host file entries, at least!) are created for both SharePoint and ADFS servers, So that both ADFS and SharePoint can identify and communicate between them selves.
  5. Service account - Have a dedicated service account for ADFS service - Must be a Local Admin account and SPN to be set on the service account: setspn -a host/adfs.crescent.com crescent\AdfsSvc
Here is our environment setup:
In production environments, ADFS infrastructure is created as a separate farm with ADFS Proxy server. For evaluation purpose, I'm using below configurations:
  • ADFS Server - ADFS.Crescent.com
  • SharePoint Farm - Web Application: Intranet.Crescent.com  
  • Certificates 
    • Intranet.Crescent.com - SharePoint web application certificate
    • ADFS.Crescent.com - Certificate for ADFS server to communicate securely.
    • TokenSigning.Crescent.com - ADFS Token signing certificate.

 

Step 1: Install ADFS Server Instance

In windows server 2008 R2, ADFS 2.0 was available as a separate download, But windows Server 2012 is built-in with ADFS capability. So, all you have to do is: Add AD FS server role by running the "Add server role wizard!". ADFS Server can be installed as a standalone or as a ADFS farm with multiple servers.  if standalone, it uses "Windows Internal database", SQL Server is used otherwise.
Although its possible to have the ADFS server in Same SharePoint box, Microsoft doesn't recommends it.

Lets begin installing ADFS Server role.
  1. Login to your proposed ADFS server. Make sure its already joined to the AD Domain. Open Server Manager
  2. Click on "Add roles and features" link from Dashboard section of the Server Manager.
  3. You'll be presented with "Add Roles and Features Wizard" . Click "Next" to start
  4. Choose "Role-based or feature-based installation" on installation Type and click "Next"
  5. Select the appropriate Server in server selection
  6. Check "Active Directory Federation Services" Server Roles and click "Next"
  7. In Features page, Make sure ".Net Framework 3.5" is already installed. if not, Select that check box.
  8. Click "Next" on AD FS page
  9. Choose "Federation Service" under Role Services section
  10. Click on "Install" button to start installing ADFS Server role.
  11. Wait for the installation to complete. Click on "Close" button to exit from the wizard.
Configure ADFS Server:
  1.  Go to Server Manager, Click on "AD FS" tab. There will be a notification at the top saying "Configuration required for Federation service". Click on "More" link, that pops up a message.
  2. Click on "Run the AD FS Management snap-in" link to run Post-deployment configuration wizard.
  3.  Now, we got into ADFS snap-in. Click on "AD FS Federation Server configuration Wizard" link to start configuring ADFS.
  4. Choose "Create a new Federation Service" option in welcome screen.
  5. Select the deployment type as "Stand-alone Federation Server"
  6. Choose the appropriate SSL Certificate for ADFS communication
  7. Click "Next" on the summary page
  8. Wait for the AD FS configuration to complete.
Verify ADFS installation:
Try navigating to any of the below URL. You should get a XML file.
  • https://YourADFS-Server.com/adfs/ls/IdpInitiatedSignon.aspx
  • https://<<servername>>/FederationMetadata/2007-06/federationmetadata.xml

 

Step 2: Create trusted relying party in ADFS 

Now, the next step is to add new trusted relying party (in our case, its our SharePoint site URL). We'll have to set up ADSFS to allow our SharePoint web sites as a Relying Parties so that SharePoint will consume claims from ADFS server.

Configure ADFS for SharePoint 2013:
Lets Add SharePoint Web Application URL as a Trusted Relying Party:
  1. Go to Server Manager, Click on "AD FS Management" from tools menu.
  2. From AD FS snap-in, Click on "Required: Add a trusted replying party" link. You can also click on "Add Relying party Trust" to get the same.
  3. Click "Start" button to initiate relying party trust wizard.
  4. In "Select Data Source" tab, choose "Enter data about the relying party manually" and click "Next"
  5. Give a display name to the relying party.
  6. Choose profile as "AD FS Profile"
  7. Token signing certificate is optional. So, we can skip it by pressing "Next" button
  8. Here is an important step: Configure URL! Select "Enable support for the WS-Federation Passive protocol" check-box. Enter the relying party WS-Federation passive protocol URL by appending : /_trust/ with your SharePoint web application. In my case, My web application is: https://intranet.crescent.com. So, I'm entering:  https://intranet.crescent.com/_trust/
  9. Configure identifiers: Enter the relying party trust identifier. It uses the naming convention of : URN:Your-Web-App. Lets enter "urn:intranet:crescent" and click on "Add" button
  10. For issuance authorization rules, choose "Permit all users to access this relying party" and click Next.
  11. Click "Next" on the summary page.
  12. Enable "Open the Edit Claim Rules dialog for this relying party trust when the wizard closes" check box, and click on "Close" button.
Edit Claims Rule:
SharePoint Claims-based authentication - authenticates users based on these set of claims, such as User principle name, E-Mail address, etc.
  1. Click on "Add Rules" button in Edit Claim Rules window.
  2. Choose the Claim rule template as: "Send LDAP Attributes as Claims"
  3. Give a Name to your claim rule, Choose the attribute store as "Active Directory", Map the attributes to be sent to SharePoint from Active Directory via ADFS. I've selected "Email-Addresses" with "E-Mail Address" and "User-Princila-Name" with "UPN". Click "Finish" button once done.
Repeat the relying party wizard for all of your web applications.

Change the Token Signing Certificate in ADFS Server
We must have different SSL certificates for "ADFS communication certificate" , "ADFS token signing certificate". we have to disable the AD FS automatic certificate rollover feature to add a token signing certificate.
Open PowerShell on the Federation Server (VSrvFs) and run the following command:
Set-ADFSProperties -AutocertificateRollover $false
Now, from the ADFS console Service >> Certificates >> Add Token-Signing Certificate >> You'll be prompted with a menu to choose a certificate >> Select the "TokenSigning.crescent.com" certificate and mark it as primary.

Remember, You must export this ADFS token signing certificate to all SharePoint servers to establish trust.

Private Key Permissions:
The service account needs to have "Read" permissions at least on the private key of the Token signing certificate. From the certificates snap-in, Browse to personal >> certificates. Right click Your token signing certificate > All Tasks > Manage Private Keys >> Grant "Read" permission to the service account 

Export this ADFS token signing certificate to all SharePoint server(s)

ADFS Token signing certificate must be exported from ADFS server and used while creating trust in  SharePoint Server. Here is how:
  1. From ADFS console, Expand "Certificates" folder, Right Click on your ADFS token signing certificate and choose "View Certificate".
  2. Under the "Details" tab, Click on "Copy to file" button. 
  3. For Export Private key section, choose "No, do not export the private key"
  4. Click "Next". Choose export file format as "DER Encoded binary x.509 (.CER)"
  5. This will export the certificate from ADFS. 

 

Step 3: Configure SharePoint 2013 to Trust ADFS

As a final step, Lets create a trusted identity token issuer pointing to ADFS as the claims provider, using PowerShell

Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue

#Register the Token Signing certificate from ADFS Server to establish Trust between SharePoint and ADFS server
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2("C:\ADFS.TokenSigning.cer") 
New-SPTrustedRootAuthority -Name "ADFS Token Signing Certificate" -Certificate $cert

#Map the claims attributes
$EmailMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" -IncomingClaimTypeDisplayName "EmailAddress" -SameAsIncoming

$UPNMap = New-SPClaimTypeMapping -IncomingClaimType "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn" -IncomingClaimTypeDisplayName "UPN" -SameAsIncoming
 
$realm = "urn:intranet:crescent"

#Sign-in URL will be ADFS Server instance
$signInURL="https://adfs.crescent.com/adfs/ls"

#Create new trusted identity token issuer
$TrustedIdentity = New-SPTrustedIdentityTokenIssuer -Name "Crescent.com" -Description "ADFS Trusted users from Crescent.com Domain" -realm $realm -ImportTrustCertificate $cert -ClaimsMappings $EmailMap,$upnMap -SignInUrl $signInURL -IdentifierClaim $Emailmap.InputClaimType
The first two lines of the above code, registers the certificate in SharePoint certificate store. Moreover, You may have to do this for Root Certificate Authority as well. You can see them under "Manage Trusts" link in security section of central administration.

Realm - is a identifier which helps ADFS to load respective configuration for a particular profile. which uses the convention of: urn:yourwebapp:yourdomain (can be anything, technically. It just uniquely identifies between multiple web applications)

IdentifierClaim - is the unique ID that identifies users in SharePoint. So,when users logged in via ADFS, they'll be identified by Email id in this case. Also, when granting access to SharePoint sites from ADFS, we'll have to use this identifier as user names. Make sure that the mapped claims exists in the source. E.g. If E-mail is mapped as Identifierclaim, then It must be exists in AD. In other worlds, E-mail field must contain a value, shouldn't be null!

SharePoint 2013 ADFS with multiple web applications 
So, You have established trusted identity provider for your primary web applications, and all other  web apps as well, say for e.g. My sites. Now, You'll have to add them in your trusted identity provider with this PowerShell code:
Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue

$TrustedIdentifyProvider = Get-SPTrustedIdentityTokenIssuer "Crescent.com"

$uri = New-Object System.Uri("https://mysites.crescent.com/")

$TrustedIdentifyProvider.ProviderRealms.Add($uri, "urn:mysite:crescent")

$TrustedIdentifyProvider.Update()

Configure SharePoint Web Application:
Next step is to enable ADFS claims in SharePoint. 
  • Go to Central Administration > Application Management > Manage Web Applications.
  • Click on "Authentication Providers" button from the ribbon
  • Select the "Default" link from the list
  • Scroll down and pick the authentication provider we just created.
  • Click "Ok" to save your changes.

Grant ADFS users Permission to the SharePoint web application
When you add permission for the user in SharePoint you have to add it as the IdentifierClaim (for example if the identifier is the email - you should add the user as user@contoso.com from SharePoint side and login with Domain\userName format.). If you skip this step, users from ADFS will get: access denied!

and when users hit SharePoint URL, They'll be presented with the default sign-in page
Troubleshooting?
Errors? Event log is the best place to start debugging!.

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


Friday, August 22, 2014

SharePoint 2013 Warmup Scripts using PowerShell

What is "Warmup Scripts" in SharePoint?
By default IIS applications pools recycles every night to keep clean memory space -  Every time during IIS Application pool recycles - Asp.net assemblies to be re-compiled to serve the page to end user. So, When the recycling occurs during mid night (or when you do manual recycling/IISReset), The very first user types the URL, experiences the wait time of 30 seconds to 120 seconds on an average. (again, this depends on your hardware-software configurations!). But the subsequent requests come faster from the server for the same site!

So, the idea is: "warm up" the site before users start requesting it so that they don't suffer at first time hit.  Warm up scripts triggers  requests to your servers regularly to "Warmup" IIS.

Ok, Where is the script? which warm up script I've to use? Well, There are lot many available. Here is one among them: https://spbestwarmup.codeplex.com/ and You may have to customize it based on your requirement.

In my experience, This simple warmup script works amazing with all versions of SharePoint: SharePoint 2013, SharePoint 2010 and in SharePoint 2007:

Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

function Get-WebPage([string]$url,[System.Net.NetworkCredential]$cred=$null) 
{ 
    $WebClient = new-object net.webclient 
    if($cred -eq $null) 
    { 
        $cred = [System.Net.CredentialCache]::DefaultCredentials; 
    } 
    $WebClient.credentials = $cred; 
    return $WebClient.DownloadString($url); 
} # end Function 

# Make sure the account has enough permission to read sites
$cred = [System.Net.CredentialCache]::DefaultCredentials; 
#If you need to use an another account
#$cred = new-object System.Net.NetworkCredential("USER ID","PASSWORD","DOMAIN")

#Get All Web Applications and iterate through
$WebAppsColl = Get-SPWebApplication -IncludeCentralAdministration

foreach($WebApp in $WebAppsColl)
{
    #Get All site collections and iterate through
    $SitesColl = $WebApp.Sites

    foreach ($Site in $SitesColl) 
    {
 Write-Host "Warming up Site collection:"  $Site.URL
 $html = Get-WebPage -url $Site.URL  -cred $cred 
    }

#Change these URL's if you need any other Site/URL for warmup
#$html = Get-WebPage -url "http://northwind.crescent.com/SitePages/Home.aspx" -cred $cred 
}
You'll have to add each of your web application to the above list of URLs. For Search web application, You'll have to send a Search query, such as: https://intranet.contoso.com/_layouts/OSSSearchResults.aspx?k=warmup

You have to edit your host files, so that Your Warmup script hits the same WFE server its running, instead of going to the load balancer and gets pages from any other web server.

Warmup Script for Host-Named Site Collections:
Lets add bit more enhancement to it:
  • Lets keep a log for warmed up sites, 
  • Warm-up all Host-named site collections - Lets create a proxy to hit on the SAME web front end rather going to load balancer - We can't edit HOST file for each HNSC, isn't it?
start-transcript -path C:\Scripts\$(get-date -format 'ddMMyyyy').txt -append

Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue  

function Get-WebPage([string]$url)
{   
    $bypassonlocal = $false
    $proxyuri = "http://" + $env:COMPUTERNAME
    $proxy = New-Object system.Net.WebProxy($proxyuri, $bypassonlocal)
    $wc = new-object net.webclient
    $wc.credentials = [System.Net.CredentialCache]::DefaultCredentials
    $wc.proxy = $proxy
    $pageContents = $wc.DownloadString($url)
    #write-host $wc.ResponseHeaders.Get("WFE")
    $wc.Dispose()
    return $pageContents
}

#Central Administration
write-host "Warming up Central Administration..."
$WebApps = Get-SPWebApplication -IncludeCentralAdministration
Get-SPWebApplication -IncludeCentralAdministration | ? {$_.IsAdministrationWebApplication -eq $true} | % { $Req = Get-WebPage $_.url }
write-host "`nCentral Administration Warmed up!"

# Warm up Host Name Site Collections (HNSC)
 Write-Host "Warming up Host Name Site Collections (HNSC)...`n"
 $hnsc = Get-SPSite -Limit All |? {$_.HostHeaderIsSiteName -eq $true} | Select Url
 foreach ($sc in $hnsc) {
        write-host "Processing HNSC: "$sc.Url
  $Req = Get-WebPage $sc.url  
 }

# Clean Temporary Files
 Remove-item "$env:systemroot\system32\config\systemprofile\appdata\local\microsoft\Windows\temporary internet files\content.ie5\*.*" -Recurse -ErrorAction SilentlyContinue
 Remove-item "$env:systemroot\syswow64\config\systemprofile\appdata\local\microsoft\Windows\temporary internet files\content.ie5\*.*" -Recurse -ErrorAction SilentlyContinue

stop-transcript

When and How often we've to run Warm up Scripts?
Usually, We schedule it to run before the beginning of the day. Its a good idea to schedule the PowerShell script via Task scheduler and Warmup script must be scheduled on all WFEs of your SharePoint Farm.

Here is how you can schedule PowerShell scripts using Windows task scheduler: Create a Scheduled Task for PowerShell Script with Windows Task Scheduler
Use "Search Crawl Account"to run warm-up script (Provided, This account has "Login as a Batch Job rights!").

You can create a scheduled task with command line:
schtasks /create /tn "Warmup Script" /ru <<Domain\Account>> /rp <<Password>> /rl highest /sc daily /st 01:00 /ri 60 /du 24:00 /tr "PowerShell.exe -ExecutionPolicy Bypass D:\Scripts\Warmup.ps1"  


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


Save Site as Template in Sharepoint 2013 using PowerShell

The most easiest way to create a standard template for your SharePoint sites is to Create a site,  Add-remove content, list and libraries to it and save site as a template from Site Settings >> Save Site as template. - Shortcut URL: "/_layouts/savetmpl.aspx"
Save Site as Template in Sharepoint 2013 using PowerShell

Save Site as Template in SharePoint 2013 using PowerShell
You can save your site as template even with the publishing feature using the following PowerShell command
$WebURL = "http://your-site-collection-URL"

#Get the Web Object
$Web= Get-SPWeb $WebURL

#Variables for Save site as template settings
$TemplateName ="PMO Site Template"
$TemplateTitle ="PMO Project Site Template" 
$TemplateDescription ="Site template for PMO project management portal"

#Option to Save with content
$SaveWithContent= 1  #0 otherwise

#Save site as template programmatically with PowerShell
$Web.SaveAsTemplate($TemplateName,$TemplateTitle,$TemplateDescription,$SaveWithContent)
Saved template will be available under site collection "Solutions" gallery. Once saved, you can import this WSP (it was .stp in SharePoint 2007 days!) file from the solution gallery into Visual Studio and customize it further. You can also upload the WSP file to other site collections to add this new site template.

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


Create SharePoint Service Accounts in AD using PowerShell

I do a lot of SharePoint deployments now a days. I use PowerShell scripts to quickly create SharePoint service accounts instead of manually creating them in Active directory one by one. Run the below PowerShell script from domain controller (or from Remote Server Administration Tools installed workstation) to create service accounts in one-short.

Here is the list of Service accounts I use in my SharePoint 2013/SharePoint 2010 deployments:
  1. SP_Setup - SharePoint Setup account
  2. SP_Farm    - SharePoint Farm account
  3. SP_Pool    - The account is used to run the Web Application Pools
  4. SP_Services - The Services Account is used to run the Service Applications
  5. SP_Crawl - The Default Content Access Account for the Search Service Application
  6. SP_UserProfile - The User Profile Import and Synchronization Account
  7. SP_SuperUser - Cache account for Web application super User account
  8. SP_SuperReader - Cache account for Web application super reader account
  9. SQL_Admin - SQL Admin on the SQL Server. Used to Install the SQL Server.
  10. SQL_Services - Service account to run SQL Server services
Here is the PowerShell script to create SharePoint Service Accounts in Active directory:
Import-Module ActiveDirectory -ErrorAction SilentlyContinue

#Set configurations
$AccountPassword = "Password1"
#Convert to Secure string 
$Password = ConvertTo-SecureString -AsPlainText $AccountPassword -Force

$Domain = "YourDomain.com"
#Specify the OU
$AccountPath= "ou=SharePoint,DC=YourDomain,DC=com"

#Create SharePoint Accounts
$Account="SP_Setup" 
New-ADUser -SamAccountName $Account -name $Account -UserPrincipalName $Account@$domain -Accountpassword $Password -Enabled $true -PasswordNeverExpires $true -path $AccountPath -OtherAttributes @{Description="Account Used to install SharePoint"}

$Account="SP_Farm" 
New-ADUser -SamAccountName $Account -name $Account -UserPrincipalName $Account@$domain -Accountpassword $Password -Enabled $true -PasswordNeverExpires $true -path $AccountPath -OtherAttributes @{Description="SharePoint Farm Account."}

$Account="SP_Pool" 
New-ADUser -SamAccountName $Account -name $Account -UserPrincipalName $Account@$domain -Accountpassword $Password -Enabled $true -PasswordNeverExpires $true -path $AccountPath -OtherAttributes @{Description="SharePoint Web Application Pools Account"}

$Account="SP_Services" 
New-ADUser -SamAccountName $Account -name $Account -UserPrincipalName $Account@$domain -Accountpassword $Password -Enabled $true -PasswordNeverExpires $true -path $AccountPath -OtherAttributes @{Description="Account to run the Service Applications"}

$Account="SP_Crawl" 
New-ADUser -SamAccountName $Account -name $Account -UserPrincipalName $Account@$domain -Accountpassword $Password -Enabled $true -PasswordNeverExpires $true -path $AccountPath -OtherAttributes @{Description="Content Access Account for the Search Service Application"}

$Account="SP_UserProfile" 
New-ADUser -SamAccountName $Account -name $Account -UserPrincipalName $Account@$domain -Accountpassword $Password -Enabled $true -PasswordNeverExpires $true -path $AccountPath -OtherAttributes @{Description="User Profile Import and Synchronization Account"}

$Account="SP_SuperUser" 
New-ADUser -SamAccountName $Account -name $Account -UserPrincipalName $Account@$domain -Accountpassword $Password -Enabled $true -PasswordNeverExpires $true -path $AccountPath -OtherAttributes @{Description="Web application super User account"}

$Account="SP_SuperReader" 
New-ADUser -SamAccountName $Account -name $Account -UserPrincipalName $Account@$domain -Accountpassword $Password -Enabled $true -PasswordNeverExpires $true -path $AccountPath -OtherAttributes @{Description=" Web application super reader account"}

$Account="SQL_Admin" 
New-ADUser -SamAccountName $Account -name $Account -UserPrincipalName $Account@$domain -Accountpassword $Password -Enabled $true -PasswordNeverExpires $true -path $AccountPath -OtherAttributes @{Description="SQL Server Admin Account"}

$Account="SQL_Services" 
New-ADUser -SamAccountName $Account -name $Account -UserPrincipalName $Account@$domain -Accountpassword $Password -Enabled $true -PasswordNeverExpires $true -path $AccountPath -OtherAttributes @{Description="Account to run SQL Server services"}
Here I'm directly specifying accounts in the PowerShell script. However, You can also use CSV files to import list of service accounts and create them in bulk in active directory.

Create SharePoint Service Accounts from CSV
Here is my CSV file with accounts, passwords and descriptions filled:

PowerShell script to Create AD accounts from CSV:
Import-Module ActiveDirectory -ErrorAction SilentlyContinue

#Set configurations
$Domain = "YourDomain.com"
#Specify the OU
$AccountPath= "ou=SharePoint,DC=YourDomain,DC=com"

# Import the CSV File
$ServiceAccounts = Import-Csv D:\SharePoint\ServiceAccounts.csv

Foreach ($ServiceAccount in $ServiceAccounts) 
 {   
    write-host "Creating Account:"$ServiceAccount.Account
    write-host "Creating Account:"$ServiceAccount.password

    #Convert to password to Secure string 
    $AccountPassword = ConvertTo-SecureString -AsPlainText $ServiceAccount.Password -Force

    $UPN = "$($ServiceAccount.Account)@$($domain)"

    #Create SharePoint Service Accounts from CSV
    New-ADUser -SamAccountName $ServiceAccount.Account -name $ServiceAccount.Account -UserPrincipalName $UPN -Accountpassword $AccountPassword -Enabled $true -PasswordNeverExpires $true -path $AccountPath -OtherAttributes @{Description=$ServiceAccount.Description}
 }


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


Wednesday, August 20, 2014

How to Change Managed Account Password in SharePoint 2013

You may have to change your service account passwords for reasons such as: Password expiration, Security best practice, Your SharePoint guy left your company, etc. Remember those old days? You got to run stsadm -o updatefarmcredentials and update application pool accounts on every server in the farm?

Luckily, we got managed accounts feature starting from SharePoint 2010 onwards. The primary advantage of the managed accounts idea is: To centrally manage service accounts of SharePoint in one place, by registering and mapping them with  SharePoint Services such as: Farm, Service Applications, Application Pools, etc. So, whenever you need to change the service account's password, Update them once!

There are three different cases to change managed account passwords in SharePoint 2013 either from SharePoint Central Administration or using PowerShell.
  1.     Generating new password
  2.     Set account password to new value
  3.     Use existing password - This option lets us updating the account password in SharePoint, if it is changed in Active Directory(or somewhere!)
Change Managed Account Password in SharePoint 2013
Case 1: Change password of the Managed account to a new random password:
If you want the password to be changed to an automatically generated random password, Use the "Generate new password" option.

To reset managed account password SharePoint 2013 with PowerShell:
Set-SPManagedAccount –Identity domain\user -AutoGeneratePassword $true

Case 2: Change Password of the Managed account in SharePoint as well as in AD
If you want to change the service password to a specific value, select the option "Set account password to new value" and enter the new password.

You can change managed account passwords in SharePoint 2010/2013 using PowerShell as:
$ManagedAccount = Read-Host "Enter the Managed account in Domain\User Format:"

#$ManagedAccount = Get-SPManagedAccount -Identity “sharepoint\sa-spcontent”
#Get new Password for the managed account
$Password = Read-Host "Enter new password for managed account" –AsSecureString

#Change the password for the managed account
Set-SPManagedAccount -Identity $ManagedAccount -NewPassword $Password

When you try to change managed account password in SharePoint 2013k, You may get the error:
"Set-SPManagedAccount: The password does not meet the password policy requirements. Check the minimum password length, password complexity and password history requirements"
Apparently, the given password is not satisfying your AD domain's password policy. Just check with your AD admin to get the password policy insights.

Case 3: Update the password of the Managed Account, which is updated in AD:
If you / AD admin has already changed the service password in active directory, you have to update it in SharePoint. Select "Use existing password" option and then enter the password

To update managed account passwords in SharePoint  2013, using PowerShell:
$ManagedAccount = Read-Host "Enter the Managed account in Domain\User Format:"

#Get new Password for the managed account
$Password = Read-Host "Enter new password for managed account" –AsSecureString

#Change the password for the managed account
Set-SPManagedAccount -Identity $ManagedAccount -ExistingPassword $Password -UseExistingPassword $true
If you get access denied error on changing password of managed account in SharePoint 2013 or in SharePoint 2010, one possible reason could be: "User cannot change password" settings.
change managed account password sharepoint 2010



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


Create New Managed Account in SharePoint 2013 Using Powershell

Managed accounts are active directory accounts for SharePoint's whose credentials are managed by SharePoint. Managed accounts in SharePoint 2013 is explained in my another article: Configuring Managed Accounts in SharePoint 2013.
Important: Before creating a managed account, They must be already created in your Active directory.
To register new managed account in SharePoint 2013, here are the steps:
  1. Open Central administration.
  2. Go Security >> Click on Configure Managed Accounts.
  3. Click the Register Managed Account link to create a new managed account.
  4. Enter the account’s AD username in domain\username format. Specify the account's password.
  5. Optionally, You can enable the automatic password reset.
  6. Click "OK" to to create managed account in SharePoint 2013.
    create managed account sharepoint 2013 powershell
Important: To register managed account SharePoint 2013, You must be a member of Farm Administrators SharePoint group.

To create a managed account using PowerShell: use the New-SPManagedAccount cmdlet. Here is how:
$cred = Get-Credential
New-SPManagedAccount –Credential $cred
This prompts to enter credentials and register managed account in SharePoint 2010/2013.

Register new managed accounts SharePoint 2013 in Bulk:
Lets create multiple Managed accounts in SharePoint 2013 in bulk:
Add-PSSnapin microsoft.sharepoint.powershell -ea SilentlyContinue

#Define a common password for all service accounts
$password = "Password1"
$securePassword = ConvertTo-SecureString -String $password -AsPlainText -Force

#List of Service accounts
$ServiceAccounts = "SP-Farm","SP_Services","SP_Search","SP_UserProfile"

   ForEach ($Account in $ServiceAccounts) 
   {
    #Get the account in Domain\UserName format
    $userName = $env:USERDOMAIN + "\" + $Account
    #Set the Credentials
    $cred = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $securePassword
    #Create Managed Account
    New-SPManagedAccount -Credential $cred
    }
Here, I've specified a common password for all managed account. However, you  can specify different passwords for different service accounts.

Troubleshooting: 

While trying to add managed account in SharePoint 2010 or in SharePoint 2013, You may encounter the below issues:

SharePoint register managed account access denied: unable to register managed account 
You may get access denied error when you try to register a managed account via Central Administration, You'll get this error: >> Security >> Configure Managed Account >> Register Managed Account.
  • Make sure either you are running SharePoint Management shell as administrator or UAC is disabled prior executing PowerShell cmdlets. 
  • Verify that your service account is allowed to change password from its properties -  “User cannot change password” !
  • if "Automatic Password reset" property is already enabled for your managed account, you may get "Access denied" error! Remove that existing account and crate a new one.
  • Use PowerShell to register new managed account!
SharePoint managed account requested registry access is not allowed:
Fix: Your Central administration App pool Identity must be a Farm Admin account also a LOCAL Administrator account

The given key was not present in the dictionary when register managed account in SharePoint 2013
Fix - KB: http://support.microsoft.com/kb/2463865/en-us


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


Tuesday, August 19, 2014

Limit Maximum Number of Site Collections in SharePoint Content Database using PowerShell

By default maximum number of site collections in a SharePoint 2013 content database is set to: 5000 and warning level will be 2000 as initial configurations. Although, technically SharePoint 2013 content database can hold up to 10,000 site collections maximum (2,500 non-Personal site collections and 7,500 Personal Sites, or 10,000 Personal Sites alone), 5000 is the recommended limit!

There are times, you may want to dedicate a database for a single site collection. When you create a site collection from central admin, site is placed automatically in any available content database. To prevent any other sites to be created on the particular content database, We can set the maximum number of sites limit! To set maximum number of site collections on a particular content database, navigate to:
  • SharePoint 2013 Central Administration >> Application Management >> Management Content databases
  • Select your target web application in which the particular content database is attached
  • Pick the target database from the list
  • Now, in the "Manage Content Database Settings" page you can set the maximum number of sites for the content database.
Limit Maximum Number of Site Collections in sharepoint
Make sure your maximum number of sites is greater than or equal to current number of sites.

PowerShell script to set Maximum number of site collection limit:
This setting should be configured for each and every content database attached with the particular web application. When you have large number of  content databases, you can use the below PowerShell script tp set max number of sites in a single stretch.
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Variables for processing
$WebAppURL ="https://Hosting.Crescent.com"
$MaxSiteCount=1
$WarningSiteCount = 0

#Get all content databases of the web application
$ContentDBColl = Get-SPContentDatabase -webapplication $WebAppURL

#Iterate through each database in the web application
foreach($Database in $ContentDBColl) 
{
    #Check the current No. of sites 
    if($MaxSiteCount -ge $Database.CurrentSiteCount)
    {
        #Set Maximum Sites, warning level Counts
        Set-SPContentDatabase -Identity $Database.Name -MaxSiteCount $MaxSiteCount -WarningSiteCount $WarningSiteCount
        Write-host "Max Sites Settings updated for the database:" $Database.name -ForegroundColor Green
    }
    else
    {
        write-host "MaxSiteCount must be > = current site count! No changes made in $($Database.Name)" -ForegroundColor Red
    }
}


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


Monday, August 18, 2014

"Open with Explorer" Greyed out in SharePoint 2013?

Open with Windows Explorer is Disabled in SharePoint 2013 or in SharePoint 2010? Well, Open with Explorer works only in 32 bit version of Internet Explorer! It may not work on Chrome or Firefox.
 open with explorer sharepoint 2013 disabled

Solution: 
To enable Open with explorer, Open your SharePoint 2010 or SharePoint 2013 site with 32 bit version of Internet explorer,  located at: "C:\Program Files (x86)\Internet Explorer\iexplore.exe"

Getting error on clicking open with explorer in SharePoint 2013? Well, Use this checklist to resolve: Open with Windows Explorer Error and Solutions for SharePoint

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


Thursday, August 14, 2014

How to Check SQL Server Connectivity from SharePoint

How do I quickly check SQL Server connectivity from SharePoint server? Well, you can use Telnet.
telnet {SQL-Server-Name or IP} 1433

If your SQL Server listens on different port, change the default port 1433 accordingly.

Using PowerShell to test SQL server connectivity:
Or you can use PowerShell to check if SharePoint it able to connect with SQL Server:
(New-Object System.Net.Sockets.TCPClient("SQL-Server-Name",1433)).Connected 
This tells you whether the particular PORT is open on the given server.

Check SQL Server Connectivity by establishing a connection: 
Run this PowerShell script to test whether you are able to connect with SQL Server.
Function Check-SQLServerConnection([string]$serverInstance)
{
    $connectionString = "Data Source={0};Integrated Security=true;Application Name=CheckSQLServer" -f $serverInstance;
    $sqlConn = new-object("Data.SqlClient.SQLConnection") $connectionString;

    Write-Host $connectionString

    try {
        $sqlConn.Open();
        $sqlConn.Close();
        Write-Host "Connected OK"-foregroundcolor white -backgroundcolor green
    }
    catch { 
        Write-Host $_ -foregroundcolor white -backgroundcolor red
    }
    finally { 
        $sqlConn.Dispose(); 
    }
}
 #Call the function with your SQL Server Machine Name
 Check-SQLServerConnection "SP13-SQL01" 


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


How to Rename SharePoint 2013/2010 Central Admin Database to Remove GUID

When you run the SharePoint products configuration wizard right after installing SharePoint binaries, it creates SharePoint central administration database with GUIDs. E.g. SharePoint_AdminContent_a149fa83-d2b9-4ad9-9e4c-ad12f73f0dd6.

Your DBAs may not be happy with these GUIDs as they deviates from database naming standards. So, lets rename SharePoint Central administration content database with the following steps:
Always, Remember to backup SharePoint Central Admin database prior performing these steps.
Here is how to remove GUID from SharePoint 2013 Central Admin database in three simple steps:

Step 1. Detach Central Admin Content Database:
Detach Central Admin Content Database: (PowerShell: Dismount-SPContentDatabase)

stsadm -o deletecontentdb -url http://centraladmin:2013 -databasename SharePoint_AdminContent_a149fa83-d2b9-4ad9-9e4c-ad12f73f0dd6 -databaseserver SP13_SQL

Step 2. Rename the Content Database from SQL Server
Right click the database, Choose Properties, Select Options tab. Set the Database restricted access property to to "Single User Mode". Rename the Database by removing GUID from it (Right click the database, choose "Rename"). Now, set the database restricted access back to "Multi-User".

Step 3.Attach the renamed Content Database
Attach the renamed content database back to Central Administration web application: (PowerShell: Mount-SPContentDatabase)

stsadm -o addcontentdb -url http://centraladmin:2013 -databasename SharePoint_AdminContent 

Alternate approach to rename SharePoint database:

Alternatively, You can create a create a new content database with right naming conventions, Move all sites from the existing content database to new database and then get-rid of the old database. Here is the script:
#Create new Content Database
New-SPContentDatabase -Name SharePoint_AdminContent -WebApplication http://centraladmin:2013
Now the Central Admin should have two databases attached with it.

Lets get the IDs of those two databases:
# Get SharePoint database IDs for old and new DBs for central admin site
Get-SPWebApplication –Identity http://centraladmin:2013 | Get-SPContentDatabase | SELECT ID, Name, WebApplication | Format-List

#Note down the IDs of Original Database and New Database. 
# In my case, Old database id: c87506a9-b87d-40b8-9582-aac9ee89c8f8.  
# New Database id: 8f35dc3b-56ab-45df-a1cf-459b60aa7454

Now, Lets move all sites from Old database to New Database:
# Move central admin sites to from old Database to new SharePoint content database
Get-SPSite –ContentDatabase c633c573-966d-4362-a1f8-430fba561f11 | Move-SPSite –DestinationDatabase 8f35dc3b-56ab-45df-a1cf-459b60aa7454

#You must do an IISReset!
# Now, You can Remove OLD SharePoint admin content database using Old database ID - actually deletes the database on the SQL Server.
 Remove-SPContentDatabase -identity c633c573-966d-4362-a1f8-430fba561f11 

How to Avoid GUIDs in SharePoint Databases:
Prevention is better than cure! Always use PowerShell to to avoid GUIDs in SharePoint Databases. Do not run Products configuration wizard right after installation. Use PowerShell to create the SharePoint farm and service applications.


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