Monday, May 08, 2017

Powershell automation script to create SharePoint 2013 sites

This script picks the required data from a list "New Site Requests" which is filled by user who wants to create the site. This powershell can be used as a job to run automatically with certain interval.

cls
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
    Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

$sourceWebURL = "http://sharepoint.site.com/support"
$sourceListName = "New Site Requests"

$SendErrorNoticeToEmailID = "abc@orgsite.com;xyz@orgsite.com;pqr@orgsite.com"
$server =  "AppContent2013_SharePointSQL" ##Config DB Server
$database = "prod_sharepoint_Content" ##Config DB name

$DatePostFix = Get-Date -format "MM-dd-yyyy_hh-mm-ss"
$LogFileName = "C:\sharepointsite\NewSiteCreation\NewLogs\SiteCreationLog_" + $DatePostFix + ".csv"

$Site_Title = ""
$Site_Description = ""
$Site_URL = ""
$Template_Type = ""
$Template_Name = ""
$Primary_Administrator = ""
$Secondary_Administrator = ""
$Quota = ""
$language=""
$Site_Type = ""
$Site_UnitDept = ""
$Site_OwnCountry = ""
$Site_BusinessImpact = ""
$Site_Expirydate = ""
$Site_HasConfidentialInfo = ""
$Site_IPPProtected = ""
$Site_LegalData = ""
$Site_FuncArea = ""
$Site_isEPDP = ""
$global:URLsinError = ""
$global:dbName = ""
$global:dbAllowSitesCount = 0
$scriptError = $false
$URLsAlreadyinUse = $true

# Read List items
function GetListItemsforSiteCreation()
{
    try {
  $spSourceWeb = Get-SPWeb $sourceWebURL
  $spSourceList = $spSourceWeb.Lists[$sourceListName]
  
  $spQuery = New-Object Microsoft.SharePoint.SPQuery
                                        $camlQuery = "" +
                                                              "" +
                                                                "" +
                                                                        "" +
                                                                        "New" +
                                                                "
"+                                                                "" +
                                                                    "" +
                                                                        "" +
                                                                        "Approve Non-Encrypted" +
                                                                    "
" +                                                                                                                                         "" +
                                                                        "" +
                                                                        "Approve Encrypted" +
                                                                    "
"+                                                                                                                                   "
" +                                                                                                                              "
" +                                                            "
"
  $spQuery.Query = $camlQuery
  $spSourceItems = $spSourceList.GetItems($spQuery)
  
  $UrlsInUse = ""

  foreach ($listItem in $spSourceItems)
  {
                            try
                            {
                               $SURL = $listItem['Full URL']

                               $URLsAlreadyinUse = (Get-SPWeb $SURL -ErrorAction SilentlyContinue ) -ne $null 
                                if ($URLsAlreadyinUse)
                                {
                                    $URLsAlreadyinUseMsg = "Site ("+$listItem["Full URL"] +")  Already Exists. Item Status changed accordingly, skipping to next item.URL"  

                                    $listItem["Status"] = "Site Already Exists";
                                    $listItem.Update();

                                    "{0},{1}" -f $listItem['Full URL'], $URLsAlreadyinUseMsg |Add-Content $LogFileName

                                    $UrlsInUse = $UrlsInUse + $listItem["Full URL"] + "; "; 
                                    
                                    continue;
                                }    
                                
                                CreateSite $listItem $spSourceWeb
                            }
                            Catch [exception]
                            { 
                                # Logging the exception in log file
                                "{0},{1}" -f $listItem['Full URL'], $_.Exception.Message |Add-Content $LogFileName   
                                    $scriptError = $true   
                                 
                            }
    
}

  # List Item For Loop finished

  try 
  {
    #Send email
            $date  = Get-Date
$subject = ""
$body = ""
            
            if((-not [system.string]::IsNullOrEmpty($UrlsInUse)) -and (-not [system.string]::IsNullOrEmpty($global:URLsinError)))
            {
                $subject = "Site creation Job notification - $date Site(s) already exists & few Site(s) returned error on creation"
$body = "Following site(s) already exists :`r`n $UrlsInUse `r`n`n Following site(s) returned error on creation :`r`n $global:URLsinError"
                
                SendMail $spSourceWeb $SendErrorNoticeToEmailID $subject $body
                $scriptError = $true
            }
            elseif (-not [system.string]::IsNullOrEmpty($UrlsInUse))
            {
$subject = "Site creation Job notification - $date Site(s) already exists"
$body = "Following site(s) already exists :`r`n $UrlsInUse"

                SendMail $spSourceWeb $SendErrorNoticeToEmailID $subject $body
                $scriptError = $true   

            }                      
            elseif (-not [system.string]::IsNullOrEmpty($global:URLsinError))
            {
   $subject = "Site creation Job notification - $date : Site(s) returned error on creation"
   $body = "Following site(s) returned error on creation :`r`n $global:URLsinError"

                SendMail $spSourceWeb $SendErrorNoticeToEmailID $subject $body 
                $scriptError = $true
            }
            

        if (($URLsAlreadyinUse -ne $true) -and ($scriptError -ne $true))
        {
$subject = "Site creation Job notification - $date : Site(s) is(are) created successfully"
$body = "Site(s) is(are) created successfully"
            SendMail $spSourceWeb $SendErrorNoticeToEmailID  $subject $body
        }             
    
    }
                            Catch [exception]
                            { 
                                # Logging the exception in log file
                                "{0},{1}" -f $global:URLsinError, "Error while sending mail--" + $_.Exception.Message |Add-Content $LogFileName   
                                    $scriptError = $true   
                                 
                            }
    }
    Catch [exception]
    { 
                 # Logging the exception in log file
                "{0},{1}" -f $global:URLsinError, "Error in method ( GetListItemsforSiteCreation() )--" + $_.Exception.Message |Add-Content $LogFileName   
                    $scriptError = $true   
                                 
    }
}


function CreateSite($listItem, $web)
{

$Site_Title = ""
$Site_Description = ""
$Site_URL = ""
$Template_Type = ""
$Template_Name = ""
$Primary_Administrator = ""
$Secondary_Administrator = ""
$Quota = ""
$language=""
$Site_Type = ""
$Site_UnitDept = ""
$Site_OwnCountry = ""
$Site_BusinessImpact = ""
$Site_Expirydate = ""
$Site_HasConfidentialInfo = ""
$Site_IPPProtected = ""
$Site_LegalData = ""
$Site_FuncArea = ""
$Site_isEPDP = ""

   $scriptError = $false
  if ([string]$listItem["Site Title"] -ne $null) {
   $Site_Title = $listItem["Site Title"]
  }

    if ([string]$listItem["Site Description"] -ne $null) {
        $Site_Description = $listItem["Site Description"]
    }

    if ([string]$listItem['Full URL'] -ne $null) {
        $Site_URL = $listItem['Full URL']
    }

    if (($listItem["sharepointsite Standard template"] | Out-String) -ne $null) {
                    if ([System.Convert]::ToBoolean($listItem["sharepointsite Standard template"]) -eq $true) {
                        $Template_Type = "Standard" }

                    else {
                        $Template_Type = "User Defined" } }

    if ([string]$listItem["Site Type"] -ne $null) {
                    if ([string]$listItem["Site Type"] -eq "Teams") {
                        $Template_Name = "Team Site" }
                    elseif ([string]$listItem["Site Type"] -eq "Projects") {
                        $Template_Name = "Project Site" }
                    elseif ([string]$listItem["Site Type"] -eq  "Community") {
                        $Template_Name = "Community Site" }
                    elseif ([string]$listItem["Site Type"] -eq  "Wiki") {
                        $Template_Name = "Enterprise Wiki" }
                    #elseif ([string]$listItem["Site Type"] -eq  "Blogs") {
                        #$Template_Name = "Blog"; }
                    else {
                        $Template_Name = "" }
    }

    if (-not [system.string]::IsNullOrEmpty($listItem["Primary Owner"])) {
                            
                            $Primary = New-Object Microsoft.SharePoint.SPFieldUserValue($web, [system.string]$listItem["Primary Owner"])
                             $Primary_Administrator = $Primary.User.UserLogin
                    }
                    if (-not [system.string]::IsNullOrEmpty($listItem["Secondary Owner"])) {
                            
                            $Secondary = New-Object Microsoft.SharePoint.SPFieldUserValue($web, [system.string]$listItem["Secondary Owner"]) 
                             $Secondary_Administrator = $Secondary.User.UserLogin
                    }
                
    if ([system.string]$listItem["Site Quota"] -ne $null) {
                    $Quota = [system.string]$listItem["Site Quota"];
                    }

    if ([system.string]$listItem["LCID"] -ne $null) {
                    $language = if([system.string]$listItem["LCID"] -eq "") { [system.string]$listItem["LCID"] } else { "1033" }
                    }
                else {
                    $language = "1033" }

                if ([system.string]$listItem["Site Type"] -ne $null)
                {
                    $Site_Type = [system.string]$listItem["Site Type"];
                    if ([system.string]$listItem["Site Type"] -eq "Teams") {
                        $Site_Type = "Team" }
                    elseif ([system.string]$listItem["Site Type"] -eq "Projects") { 
                        $Site_Type = "Project"
                        }
                    elseif ([system.string]$listItem["Site Type"] -eq "Blogs") {
                        $Site_Type = "Blog"
                        }
                }    

    if (([system.string]$listItem["Owning Unit"] -ne $null) -and ([system.string]$listItem["Owning Department"] -ne $null)) {
                    $Site_UnitDept = [system.string]$listItem["Owning Unit"] + "." + [system.string]$listItem["Owning Department"] }

                if ([system.string]$listItem["Country"] -ne $null) {
                    if ([system.string]$listItem["Country"] -ne "Other") {
                        $Site_OwnCountry = [system.string]$listItem["Country"] }
                    elseif ([system.string]$listItem["Other Country"] -ne $null) {
                        $Site_OwnCountry = [system.string]$listItem["Other Country"] }

                if ([system.string]$listItem["Business Impact"] -ne $null) {
                    $Site_BusinessImpact = [system.string]$listItem["Business Impact"] }
                else {
                    $Site_BusinessImpact = "Low" }

                if ([system.string]$listItem["Site Expiration Date"] -ne "") {
                    $Site_Expirydate = ([system.string]$listItem["Site Expiration Date"]).Substring(0, ([system.string]$listItem["Site Expiration Date"]).IndexOf(" ")) }

                if ([system.string]$listItem["Confidential Info"]-ne $null) {
                    $Site_HasConfidentialInfo = if ([System.Convert]::ToBoolean($listItem["Confidential Info"])  -eq $true) { "1" } else { "0" }
                    }
                else {
                    $Site_HasConfidentialInfo = "0" }

                if ([system.string]$listItem["IPP Protected"]-ne $null) {
                    $Site_IPPProtected = if ([System.Convert]::ToBoolean($listItem["IPP Protected"])  -eq $true) { "1" } else { "0" }
                    }
                else {
                    $Site_IPPProtected = "0"
                    }

                if ([system.string]$listItem["Is Legal Data"]-ne $null) {
                    $Site_LegalData = if ([System.Convert]::ToBoolean($listItem["Is Legal Data"])  -eq $true) { "1" } else { "0" }
                    }
                else {
                    $Site_LegalData = "0"
                    }

                if ([system.string]$listItem["Functional Area"] -ne $null) {
                    $Site_FuncArea = [system.string]$listItem["Functional Area"]
                    }
                else {
                $Site_FuncArea = "";
                }

                if ([system.string]$listItem["Site Type"] -ne $null) {
                    $Site_isEPDP = if([system.string]$listItem["Custom Site Template"]  -eq "EPDP") { "1" } else { "0"}
                    }
                else {
                    $Site_isEPDP = "0"
                    }

                if ([system.string]$listItem["EPDP Program Manager"] -ne $null) {
                    $Site_EPDPprogramManager = New-Object Microsoft.SharePoint.SPFieldUserValue($web,[system.string]$listItem["EPDP Program Manager"]).User;
                    }
                else {
                    $Site_EPDPprogramManager = $null;
                    }

                if ([system.string]$listItem["EPDP Project Phase"]-ne $null) {
                    $Site_EPDPprojectPhase = [system.string]$listItem["EPDP Project Phase"]
                    }
                else {
                    $Site_EPDPprojectPhase = ""
                    }

                if ([system.string]$listItem["EPDP Product Structure"]-ne $null) {
                    $Site_EPDPproductStructure = [system.string]$listItem["EPDP Product Structure"]
                    }
                else {
                    $Site_EPDPproductStructure = ""
                    }


    # "Setting Site Template"
    $parsedSiteTemplate = Get-SPWebTemplate | where-object {($_.Title -eq "Blank Site") -and ($_.LocaleId -eq $language)}
$parsedSiteTemplateName = $parsedSiteTemplate.Name
    

    # "Setting Quota Template"
    $Quota = $Quota.Replace(" ","")
    $Quota = "quota_$Quota"
    $contentService =[Microsoft.SharePoint.Administration.SPWebService]::ContentService
    foreach ($quotaTemplate in $contentService.QuotaTemplates | ? {$_.Name.StartsWith("$Quota")} | % {$parsedQuotaTemplate = $_}) {}
   
    
    #  "Creating site collection..."
    try {
       if ($listItem["Status"] -eq "Approve Encrypted")
       {
            # Get DB Name first time, if the selected content database has not available space for sites, access another content database 
            if (([system.string]::IsNullOrEmpty($global:dbName)) -or ($global:dbAllowSitesCount -eq 0))
            {
                GetEncryptedDBName
            }                              
                                
            if($global:dbName -ne "" -and $global:dbName -ne $null) 
            {
                $global:dbAllowSitesCount = $global:dbAllowSitesCount - 1
           New-SPSite -Url $Site_Url -Name $Site_Title -Description $Site_Description -ContentDatabase $global:dbName -OwnerAlias $Primary_Administrator -SecondaryOwnerAlias $Secondary_Administrator -QuotaTemplate $parsedQuotaTemplate -Language $language -ErrorAction Stop            
            }
      }
      else 
      {
        New-SPSite -Url $Site_Url -Name $Site_Title -Description $Site_Description -OwnerAlias $Primary_Administrator -SecondaryOwnerAlias $Secondary_Administrator -QuotaTemplate $parsedQuotaTemplate -Language $language -ErrorAction Stop
 }
    }
    catch [Exception]
    {
        $scriptError = $true
        "{0},{1}" -f $listItem['Full URL'], "`nError in creating site collection.`n" + " Exception - " + $_.Exception.Message + "`n" |Add-Content $LogFileName  
        $global:URLsinError = $global:URLsinError + $listItem['Full URL'] + "; "; 
        
   #exit
    }

  if ($scriptError -eq $false) {
    
                    if ($listItem["sharepointsite Standard template"] -ne $null) {
                                        if ($listItem["sharepointsite Standard template"] -eq $false -and $listItem["Full URL"] -ne $null)
                                        {
                                             SetGroupsForSite $Site_URL
ProvisioningCustomTemplateSites $web $listItem
                                             UpdateCustomSiteMetadata $listItem $web
                                        }

                                    $listItem["Status"] = "Completed";
                                    $listItem.Update();
                                }
                                else
                                {
                                    $scriptError = $true   
                                    "{0},{1}" -f $listItem['Full URL'], "There is some error while creating site for the URL." |Add-Content $LogFileName  
                                    $global:URLsinError = $global:URLsinError + $listItem['Full URL'] + "; "; 
                                    
                                }

            "{0},{1}" -f $listItem['Full URL'], "The site is created successfully." |Add-Content $LogFileName 

     }
     
  }
}

function SetGroupsForSite ($Site_URL)
{
    $site = Get-SPSite $Site_Url
$rootWeb = $site.RootWeb

#  "Creating default groups..."

$rootWeb.AssociatedVisitorGroup = $null
$rootWeb.Update()
$rootWeb.CreateDefaultAssociatedGroups($Primary_Administrator, $Secondary_Administrator, $Site_Title)
$rootWeb.Update()

#  "Setting access request values..."
$rootWeb.RequestAccessEmail = $site.Owner.Email
$rootWeb.Update()

Enable-SPFeature -identity "ccf46f39-b9f4-4f9b-8d11-54286c42aaaa" -URL $Site_URL
Enable-SPFeature -identity "67b14c35-627a-4e09-8a2c-d69be020bbbb" -URL $Site_URL
Enable-SPFeature -identity "23c8a91c-c553-4b97-8fe3-f53e9f73cccc" -URL $Site_URL 
}


function ProvisioningCustomTemplateSites($RequestWeb, $listItem)
 {
            ## Provisioning the Custom Template. 
            ## Blank Site is created by the script for cases where User Defined Template is selected.
            ## This method provisions User Defined Template to the blank site.
            ## It also ensures that all the features of that user defined template are activated.
            try {
            $site = $listItem['Full URL'] 
            $myNewBlankSite = Get-SPSite $site  
            $myNewBlankWeb = Get-SPWeb $site        
        
                
                $requestedTempalte = [System.String]($listItem["Custom Site Template"]);
                
                if (($requestedTempalte.Equals("Wiki")) -ne  $true)
                {
                    ##Get the WSP File
                    $TempllistItem = $RequestWeb.Lists["User Defined Site Templates"] 
                    foreach($tmp in $TempllistItem.Items)
                    {
                        if ($tmp["Title"] -eq $listItem["Custom Site Template"])
                        {
                            $tmpWspName = $tmp["Name"]
                        }
                    }
                    
                    $sourceSolutionFile = $RequestWeb.GetFile("User Defined Site Templates/" + $tmpWspName.Trim())

                    ## Get the Solution Gallery for the SPSite
                    $solutionGallery = $myNewBlankSite.GetCatalog([Microsoft.SharePoint.SPListTemplateType]::SolutionCatalog);

                    ## Add the WSP File
                    $solutionFile = $solutionGallery.RootFolder.Files.Add($sourceSolutionFile.Name, $sourceSolutionFile.OpenBinary())

                    do 
                    {
                            Start-Sleep -Seconds 5;
                            try
                            {
                                $testsolution = Get-SPUserSolution -Identity $sourceSolutionFile.Name -Site $myNewBlankSite
                            }
                            catch {  
                                 "{0},{1}" -f $listItem['Full URL'], "`nError in getting user defined solution.`n" + "Exception - " + $_.Exception.Message + "`n" |Add-Content $LogFileName                                
                             }
                    }
                    while(!$testsolution);
                    
                    ## Activate Solution    
                    Install-SPUserSolution -Identity $sourceSolutionFile.Name -Site $myNewBlankSite

                    Start-Sleep -Seconds 5;

                    ## Ensuring proper activation of all features of the Custom Template Solution- Important - Get updated site object
                    $newsite = Get-SPSite -Identity $site
           $spFeatureColl = $newsite.Features
                    foreach ($spFeature in $spFeatureColl)
                    {
                        $feature = $spFeature.Definition 
                                if(($feature.SolutionId -eq $testsolution.SolutionId) -and ($feature.Scope -eq [Microsoft.Sharepoint.SPFeatureScope]:: Site))
                                {
                                     $siteFeature = Get-SPFeature -Site $newsite.Url -Identity $feature.Id -ErrorAction SilentlyContinue
                                    if ($siteFeature -ne $null) {
                                        Enable-SPFeature -Identity $feature.Id -Url $newsite.Url

                                    }
                                }
                        
                    }
                    
                    Start-Sleep -Seconds 20;

                    #**Selecting the Custom Template for the UPDATED Site Object
                    $newsite = Get-SPSite -Identity $site
                    $templatename = $tmpWspName -replace ".wsp", ""
                    $loc = [System.Int32]::Parse(1033)
                    $webTemplate = $newsite.GetWebTemplates($loc) 
                    foreach($temp in $webTemplate | ? {$_.Title -eq $templatename.Trim()} | % {$newsite.RootWeb.ApplyWebTemplate($_.Name)})
                    {}
                                    
                }
                else
                {
                    $myNewBlankSite.RootWeb.ApplyWebTemplate("WIKI#0")                                        
                }
                    
            }
            catch [Exception]{

                "{0},{1}" -f $listItem['Full URL'], "`nError setting user template .`n" + "Exception - " + $_.Exception.Message + "`n" |Add-Content $LogFileName  
            }
        }


function UpdateCustomSiteMetadata($listItem, $web) 
        {
            try
           {
                $site = $listItem['Full URL']
                $NewCreatedSite = Get-SPSite $site              
                    $NewCreatedWeb = $NewCreatedSite.RootWeb;

                ############### Initial values - START

                $NewCreatedWeb.AllProperties["__category_key__"] = $Site_Type
                $NewCreatedWeb.AllProperties["__isEPDP_key__"] = $Site_isEPDP

                if (-not [system.string]::IsNullOrEmpty($Site_EPDPprogramManager))
                {
                $NewCreatedWeb.AllProperties["__EPDPprogramManager_key__"] = $Site_EPDPprogramManager
                }
                if (-not [system.string]::IsNullOrEmpty($Site_EPDPprojectPhase))
                {
                $NewCreatedWeb.AllProperties["__EPDPprojectPhase_key__"] = $Site_EPDPprojectPhase
                }
                if (-not [system.string]::IsNullOrEmpty($Site_EPDPproductStructure))
                {
                    $NewCreatedWeb.AllProperties["__EPDPproductStructure_key__"] = $Site_EPDPproductStructure
                }

                #$NewCreatedWeb.AllProperties["__legal_data_key__"] = $Site_LegalData

                $NewCreatedWeb.Update()

                ############### Initial Values - END

                $Site_UnitDept = ""   
                $Site_OwnCountry = ""   
                $Site_BusinessImpact = ""   
                $Site_Expirydate = ""   
                $Site_HasConfidentialInfo = ""   
                $Site_IPPProtected = "0"   
                $Site_LegalData = "0"   
                $Site_FuncArea = ""   
                $Site_isEPDP = "0"   
                $Site_EPDPprogramManager = $null;
                $Site_EPDPprojectPhase = ""   
                $Site_EPDPproductStructure = ""

                if ([String]($listItem["Owning Unit"]) -ne $null -and [String]($listItem["Owning Department"]) -ne $null) {
                  $Site_UnitDept = [String]($listItem["Owning Unit"]) + "." + [String]($listItem["Owning Department"]);
                  }
                if ([String]($listItem["Country"]) -ne $null)
                { 
                    if ([String]($listItem["Country"]) -ne "Other")
                    {
                      $Site_OwnCountry = [String]($listItem["Country"]);
                     }
                    elseif ([String]($listItem["Other Country"]) -ne $null)
                    {
                      $Site_OwnCountry = [String]($listItem["Other Country"]);
                    }
                }
                if ([String]($listItem["Business Impact"]) -ne $null) {
                  $Site_BusinessImpact = [String]($listItem["Business Impact"]); }
               else  {
                  $Site_BusinessImpact = "Low"   }
                  
                if ([String]($listItem["Site Expiration Date"]) -ne $null) {
                  $Site_Expirydate = ([system.string]$listItem["Site Expiration Date"]).Substring(0, ([system.string]$listItem["Site Expiration Date"]).IndexOf(" ")) 

                  }
                if ([String]($listItem["Confidential Info"]) -ne $null) {
                  $Site_HasConfidentialInfo = if ([System.Convert]::ToBoolean($listItem["Confidential Info"]) -eq $true) { "1" } else { "0"   }
                  
                }  else {
                  $Site_HasConfidentialInfo = "0"   
                  }
                if ([String]($listItem["IPP Protected"]) -ne $null) {
                  $Site_IPPProtected = if ([System.Convert]::ToBoolean($listItem["IPP Protected"]) -eq $true) { "1" }   else  { "0" }
                  }
                  else  {
                  $Site_IPPProtected = "0"   }
                if ([String]($listItem["Is Legal Data"]) -ne $null) {
                  $Site_LegalData = if ([System.Convert]::ToBoolean($listItem["Is Legal Data"]) -eq $true) { "1" }   else  { "0" }
                }  else {
                  $Site_LegalData = "0"   }
                if ([String]($listItem["Functional Area"]) -ne $null) {
                  $Site_FuncArea = [String]($listItem["Functional Area"]);
                }  else {
                  $Site_FuncArea = ""   }
                if ([String]($listItem["Site Type"]) -ne $null) {
                  $Site_isEPDP = if ([String]($listItem["Custom Site Template"]) -eq "EPDP") { "1" } else { "0"   }
                }  else {
                  $Site_isEPDP = "0"   }
                if ([String]($listItem["EPDP Program Manager"]) -ne $null) {
                  $Site_EPDPprogramManager = New-Object Microsoft.SharePoint.SPFieldUserValue($web, [String]($listItem["EPDP Program Manager"])).User;
                }  else {
                  $Site_EPDPprogramManager = $null; }
                if ([String]($listItem["EPDP Project Phase"]) -ne $null) {
                  $Site_EPDPprojectPhase = [String]($listItem["EPDP Project Phase"]);
                }  else {
                  $Site_EPDPprojectPhase = ""   }
                if ([String]($listItem["EPDP Product Structure"]) -ne $null) {
                  $Site_EPDPproductStructure = [String]($listItem["EPDP Product Structure"]);
                }  else {
                  $Site_EPDPproductStructure = ""   }

                

                    $NewCreatedWeb.AllProperties["__division_key__"] = $Site_UnitDept;
                    $NewCreatedWeb.AllProperties["__country_key__"] = $Site_OwnCountry;
                    $NewCreatedWeb.AllProperties["__group_key__"] = $Site_BusinessImpact;
                    $NewCreatedWeb.AllProperties["__expiry_key__"] = $Site_Expirydate;
                    $NewCreatedWeb.AllProperties["__expiry1_key__"] = $Site_Expirydate;
                    $NewCreatedWeb.AllProperties["__category3_key__"] = $Site_HasConfidentialInfo;
                    $NewCreatedWeb.AllProperties["__category4_key__"] = $Site_IPPProtected;
                    $NewCreatedWeb.AllProperties["__area_key__"] = $Site_FuncArea;
                    if ($Site_isEPDP -eq "1")
                    {
                        $NewCreatedWeb.AllProperties["__isEPDP_key__"] = $Site_isEPDP;
                        $NewCreatedWeb.AllProperties["__EPDPprogramManager_key__"] = $Site_EPDPprogramManager.Name;
                        $NewCreatedWeb.AllProperties["__EPDPprojectPhase_key__"] = $Site_EPDPprojectPhase;
                        $NewCreatedWeb.AllProperties["__EPDPproductStructure_key__"] = $Site_EPDPproductStructure;
                    }
                    if ($Site_LegalData -eq "1")
                    {
                        $NewCreatedWeb.AllProperties["__legal_data_key__"] = $Site_LegalData;
                    }
                    $NewCreatedWeb.AllProperties["__reviewedBy_key__"] = ""  

                    $NewCreatedWeb.AllProperties["__reviewedOn1_key__"] = ""   

                    $NewCreatedWeb.Update();
             }
            
            Catch [exception]
        { 
            # Logging the exception in log file
            "{0},{1}" -f $listItem['Full URL'], $_.Exception.Message |Add-Content $LogFileName    
        }
    
                               
     }


function SendMail($web, $EmailTo, $Subject, $Body)
{
            #

            #Send an email from a SharePoint Web
            #

            [Microsoft.SharePoint.Utilities.SPUtility]::SendEmail($web, $false, $false, $EmailTo, $Subject, $Body);

}


function GetEncryptedDBName()
{     
    $connectionString = “Server=$server;Database=$database;Integrated Security=True;”
    $global:dbName = ""
    
    try 
    {
        $connection = New-Object System.Data.SqlClient.SqlConnection
        $connection.ConnectionString = $connectionString
        $connection.Open()

        $query = 
            “SELECT @@Servername, db.name, Case db.is_encrypted when '1' then 'Y' when '0' then 'N' else '0' end as Encrypted
        FROM sys.databases db
        LEFT OUTER JOIN sys.dm_database_encryption_keys dm
        ON db.database_id = dm.database_id WHERE db.is_encrypted = '1'
        ”                    
        $command = $connection.CreateCommand()
        $command.CommandText = $query

        $reader = $command.ExecuteReader();

        while($reader.read() -and ([string]::IsNullOrEmpty($global:dbName))) 
        {

            if ($reader["name"] -ne $null)
            {                                 
               try 
               {     
                                                         
                    foreach($DB in get-spcontentdatabase | ? {$_.name -eq $reader["name"]})
                    {
                        if($DB.MaximumSiteCount -gt $DB.CurrentSiteCount)
                        {
                            #DB found, create site using the $DB.name
                            $global:dbName = $DB.name
                            $global:dbAllowSitesCount = ($DB.MaximumSiteCount) - ($DB.CurrentSiteCount)

                            break;
                        }
                    } 
                }
                Catch [exception]
                {
                    # Logging the exception in log file
                    "{0},{1}" -f "Error in method: GetEncryptedDBName(). DB Name - " + $reader["name"] + ". Exception - ", $_.Exception.Message |Add-Content $LogFileName   
                }
                                                               
             }
        }
        if([string]::IsNullOrEmpty($global:dbName))
        {
            # Logging the error message in log file
            "{0},{1}" -f "Error in method: GetEncryptedDBName()", "No encrypted DB space available" |Add-Content $LogFileName              
                
        }

     }
    Catch [exception]
    {
        "{0},{1}" -f "Error in method: GetEncryptedDBName()", "SQL Can't read the Encrpted DB information" |Add-Content $LogFileName               
    }
                finally
                {
                                # Dispose the objects
                                $reader.close()
                                $connection.Close()
                }
}


GetListItemsforSiteCreation


Saturday, February 13, 2016

Powershell script to edit SPO site secondary owner using property bag values

In SharePoint Online (SPO) we cannot modify the secondary owner using SharePoint Hosted Apps so there is a work around to modify this value using powershell script.
We can save the secondary owner values in property bag and then using powershell we can update secondary owner field.

Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"  
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"  

#Log File
$DatePostFix = Get-Date -format "MM-dd-yyyy_hh-mm-ss"
$LogFileName = "SetSecondaryOwner_SPO_" + $DatePostFix + ".csv"
$LastRunDateFileName = "SetSecondaryOwner_SPO_LastRunDate.csv"
# User Credentials
$Username="abc@org.com" 
$AdminPassword = Read-Host -Prompt "Enter Password" -AsSecureString

## Site URL - Providing the credentials
$AdminUrl="https://sposite.sharepoint.com"

#Retrieve all site collection infos
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username, $AdminPassword
Connect-SPOService -Url $AdminUrl -Credential $cred
$sitesCollectionsList = Get-SPOSite 

try 
{
    # Get todays date. 
        $todayDate = Get-Date 

    # Get Script last run date
        if (!(Test-Path $LastRunDateFileName))
        {
            "{0}" -f $todayDate.AddDays(-1) |Add-Content $LastRunDateFileName  
        }
        $lastRunFile = Get-Content $LastRunDateFileName
        if ([string]::IsNullOrEmpty($lastRunFile)) {            
            $scriptLastRundate = $todayDate.AddDays(-1).ToString()
        }
        else
        {
            $scriptLastRundate = [datetime]$lastRunFile.ToString()
        }

    #Retrieve and print all sites
    foreach ($siteColl in $sitesCollectionsList)
    { 
    
      try
      {

        #SPO Client Object Model Context
        $ctx=New-Object Microsoft.SharePoint.Client.ClientContext($siteColl.Url)
        $ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $AdminPassword)
        $site=$ctx.site
        $spoRootWeb = $ctx.Web
        $ctx.Load($site)
        $ctx.Load($spoRootWeb)
        $ctx.ExecuteQuery()
        
        #Get the property bag values 
        $spoAllSiteProperties=$spoRootWeb.AllProperties
        $ctx.Load($spoAllSiteProperties)
        $ctx.ExecuteQuery()  
        
        # Check if Last Review date exist and get the value
        $lastReviewdate = ""
        if ($spoAllSiteProperties.FieldValues.ContainsKey(‘__reviewedOn_key___’)) {
            $lastReviewdate = [datetime]$spoAllSiteProperties[‘__reviewedOn_key___’]
        }

        # Update Secondary Owner if lastreview date is today's date or script last run date is lesser than the review date
        if (!([string]::IsNullOrEmpty($lastReviewdate))) {
            if (($scriptLastRundate -lt $lastReviewdate) -or ($lastReviewdate.ToShortDateString() -eq $todayDate.ToShortDateString()))
            {
                if(($spoAllSiteProperties.FieldValues.ContainsKey(‘__secondary_contact__’)) -and ($spoAllSiteProperties["__secondary_contact__"] -ne ""))
                {
                    
                $sUser = $site.RootWeb.EnsureUser($spoAllSiteProperties[‘__Secondary_Contact__’]);
                $ctx.Load($sUser);
                $ctx.ExecuteQuery()  

                # Update secondary contact
                $site.SecondaryContact = $sUser
                $site.SecondaryContact.Update();
                $ctx.ExecuteQuery();              

                }

                $ctx.Dispose()
             }
           }
        }
        Catch [exception]
        { 
            # Logging the exception in log file
            "{0},{1}" -f "Error in SetSecondaryOwner SPO script while traversing in each sitecollection. Site URL= $site.Url", $_.Exception.Message |Add-Content $LogFileName    
        }        

     }

      #Update Last Run Date CSV for script last run date
       Clear-Content $LastRunDateFileName
       "{0}" -f $todayDate |Add-Content $LastRunDateFileName  

 }
 Catch [exception]
   { 
            # Logging the exception in log file
            "{0},{1}" -f "Error in SetSecondaryOwner SPO script.", $_.Exception.Message |Add-Content $LogFileName    
   }
 finally
   {
            $ctx.Dispose()
   }