Wednesday, November 25, 2015

Create site collection with Separate content database

Steps:
1.Create Content DB through central admin
2.Put all existing Content DB into Offline.
3.now create site collection
4.Check the number of site collection count in Manually created Content DB is 1.
5.then Put all existing Content DB into Online.

Back Up the IIS Configuration

Back Up the IIS Configuration

To back up your IIS configuration, follow these steps:
  1. In the IIS snap-in on the local computer, click the Computer icon under Internet Information Services.
  2. Click Action and select Backup/Restore Configuration.
  3. Click Create backup, choose a name for your backup file, and then click OK.NOTE: The default location of the backup is the %SystemRoot%\system32\inetsrv\MetaBack folder. If you want to save your backup file to another location, you can copy the file from this default location to another location. Keep a copy in the default location to allow for an easy restoration. Note that by default, C:\Winnt is the %SystemRoot% folder in Microsoft Windows 2000.
  4. Click Close.NOTE: This backup method provides a way to restore only your IIS settings, not your content files. This backup method does not work if you reinstall your operating system. Backup files cannot be used to restore an IIS configuration on other computers that are running Windows 2000.

Restore the IIS Configuration

The steps to restore a configuration differ depending on whether you removed and reinstalled IIS. 

NOTE: If you want to restore your IIS configuration and only an older copy or no copy of the metabase file exists, see the following Microsoft Knowledge Base article:
234429 How to Manually Restore the Metabase When No Backup Exists

Restoring the IIS Configuration Without an IIS Reinstallation

To restore your IIS configuration if you have not removed and reinstalled IIS, follow these steps:
  1. In the IIS snap-in on the local computer, click the Computer icon under Internet Information Services.
  2. Click Action and select Backup/Restore Configuration.
  3. In the Configuration Backup Name dialog box, select a backup file and click Restore. When you are asked if you want to restore your configuration settings, click Yes.

Restoring the IIS Configuration After an IIS Reinstallation

To restore your IIS configuration after you have removed and reinstalled IIS, follow these steps:
  1. In the IIS snap-in on the local computer, click the Computer icon under Internet Information Services.
  2. Click Action and select Backup/Restore Configuration.
  3. In the Configuration Backup Name dialog box, select the backup file that you created and click Restore. Although an error message states that the restoration has failed, a portion of your backed-up configuration is restored.
  4. At a command prompt, type the following:
    cscript.exe X:\InetPub\AdminScripts\Adsutil.vbs enum w3svc
    where X is the letter of the drive on which IIS is installed. From the listed settings, locate the WamUserName and the associated WAMUserPass value.

    NOTE: To use the Adsutil.vbs utility, you must have Windows Script Host installed.
  5. Click Start, point to Settings, click Control Panel, double-click Administrative Tools, and then double-click Computer Management. Click Local User Managers and click Users.
  6. Double-click the IWAM_computername user account. Type the WAMUserPass value that you retrieved from the previous step and clickOK.
  7. In the Configuration Backup Name dialog box, select the backup file that you created and click Restore. This fully restores your configuration.

    NOTE: If you change the identity of your out-of-process applications, those applications revert back to the previous IWAM user name.

Yammer integration



Lync Integration



Find All Incoming E-Mail Enabled Lists and Libraries in SharePoint

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
 
$SPWebApp = Get-SPWebApplication "<a class="vglnk" href="http://sharepoint.com" rel="nofollow"><span>http</span><span>://</span><span>sharepoint</span><span>.</span><span>com</span></a>"
  
<# If it is MOSS 2007, You can use:
$SPWebApp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup(<a class="vglnk" href="http://sharepoint.com" rel="nofollow"><span>http</span><span>://</span><span>sharepoint</span><span>.</span><span>com</span></a>)
 To get SPWebApplication Object
#>
  
#create a CSV file
"E-Mail,List,Site" "EMail-Enabled.txt" #Write the Headers in to a text file
  
foreach ($SPsite in $SPwebApp.Sites)  # get the collection of site collections
{
    foreach($SPweb in $SPsite.AllWebs)  # get the collection of sub sites
        {
            foreach ($SPList in $SPweb.Lists)
                {
                    if ( ($splist.CanReceiveEmail) -and ($SPlist.EmailAlias) )
                        {
                            # WRITE-HOST "E-Mail -" $SPList.EmailAlias "is configured for the list "$SPlist.Title "in "$SPweb.Url
                            $SPList.EmailAlias + "," $SPlist.Title +"," $SPweb.Url >> EMail-Enabled.txt  #append the data
                        }
                }
        }
}


PowerShell script with parameters in scheduled task

PowerShell script with parameters in scheduled task: 
Say, We've a Parameter "$WebAppURL" in our PowerShell script:

Param(
       [parameter(Mandatory=$true)] $WebAppURL
     )
   
 # We'll trigger the script as:  .\StorageReport "http://sharepoint.crescent.com"

So in Task scheduler, Add arguments(optional), Enter: d:\scripts\StorageReport "http://sharepoint.crescent.com"

When there are multiple parameters, you can separate them by giving parameter name as key. such as:

Param(
       [parameter(Mandatory=$true)] $WebAppURL,
       [parameter(Mandatory=$true)] $OutPut
     )

# We trigger it as: StorageReport -WebAppURL "http://sharepoint.crescent.com" -output "d:\Reports\StorageReport.csv"

Create Scheduled Tasks with PowerShell:
From PowerShell 3.0 (Windows Server 2012 R2) onwards , We've a new cmdlets to create and manage Scheduled Tasks! Here is an example:
?
1
2
3
4
5
6
7
8
9
10
11
#Variables
$TaskName = "Audit Large Lists"
$username ="Crescent\SP13_FarmAdmin"
$password ="Password Here"
 
#Create Scheduled Task
$Action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "E:\Scripts\AuditLists.ps1"
$Trigger = New-ScheduledTaskTrigger -Daily -At 1am
$ScheduledTask = New-ScheduledTask -Action $action -Trigger $trigger 
 
Register-ScheduledTask -TaskName $TaskName -InputObject $ScheduledTask -User $username -Password $password 

Failed to connect to the Existing configuration database when adding server to SharePoint farm

Issue
retrieve database server and select SharePoint farm configuration database that stores all farm configuration and settings, then type pass-phrase and wait for Farm Configuration Wizardcomplete. However, what we think may not be what it will come out, and this really happens all the time.
Everything went smoothly till Farm Configuration Wizard told that the new server failed to connect to the configuration database. Something ambiguously happened I didn’t really know what was going on.
Error:
Failed to connect to the configuration database.
An exception of type System.ArgumentNullException was thrown. Additional exception information: Value cannot be null.
Parameter name: service
Soulution

I noticed that SharePoint team of the customer had created a pointer for SharePoint alias connecting to the SharePoint application server. Figured out that the new server couldn’t connect to database server through the named alias. To solve this problem, on the SharePoint application server, I navigated toC:WindowsSystem32cliconfg.exe and then checked alias configuration atAlias tab on SQL Server Client Network Utility windows.
On the new server that need to be joined to the SharePoint farm, I created a new alias using the same configuration. The error went away immediately.
I’ve experienced a few things and would like to share with you:
  • Make sure your key you type on the new server must match the licensed key used on other SharePoint servers before.
  • The account used during running Farm Configuration Wizard should be Farm Account.
  • If you use alias, make sure every server you are going to join to SharePoint farm must have same alias configuration, unless SharePoint can’t connect to configuration database.
  • Check if the new server is blocked to communicate to other servers in SharePoint farm. In case, you must work with security team to address this issue.

InfoPath - When a form is stuck on "Installing" or "Upgrading" or Deleting

When a form is stuck on "Installing" or "Upgrading"



Check timer jobs. If there are jobs that can't start - they will wait
Check all administration service are running on both servers
Check timer service is running (timer service calls administration service to deploy)
If your administration service is OFF, then you can try using the command line to execute those timer jobs
stsadm -o execadmsvcjobs
The benefit is if there's exceptions thrown here you'd see it in the console
Do this on all SharePoint servers. If the administration service is running, then this stsadm command won't do anything.
If your job is missing, you can check in Solution Management /_admin/Solutions.aspx
Go to Solution Management under Central Administration /_admin/Solutions.aspx
Find the farm solutions that for the form. The name would be form-formname.wsp.
If the solution isn't deployed, you can select deploy - global
If your admin service isn't running, you'll get a warning saying that jobs are scheduled but no admin service means they won't run.
Use stsadm -o execadmsvcjobs
If nothing else works, or if we want to do a complete removal.
In form templates, select the form template, and hit Remove.
Form is stuck on "Deleting"

Go to Solution Management under Central Administration /_admin/Solutions.aspx
Find the farm solutions that for the form. The name would be form-formname.wsp.
If the status is Deployed, then retraction hasn't started.
Click the package and select Retract Solution.
If your admin service isn't running, you'll get a warning saying that job is scheduled but no admin service means they won't run.
In command line, stsadm -o execadmsvcjobs, on both servers.
C:\ > stsadm -o execadmsvcjobs
Executing job-application-server-admin-service.
Executing job-password-management.
Executing solution-deployment-form-tradepackageform.wsp-0.
Operation completed successfully.
You'll see this back on solutions. 
Name:    form-packageform.wsp 
Type:    Core Solution 
Contains Web Application Resource:    No 
Contains Global Assembly:    No 
Contains Code Access Security Policy:    No 
Deployment Server Type:    Front-end Web server 
Deployment Status:    Deployed 
Deployed To:    Globally deployed. 
Last Operation Result:    The solution was successfully retracted. 
Last Operation Details:    
SRV02 : The solution was successfully retracted. 
SRV03 : The solution was successfully retracted. 
Last Operation Time:    1/8/2013 11:01 AM 

You can then remove the solution package.
If you go back to Form Template management, the form will be removed from the list, and you can re-upload as usual.

The solution cannot be removed when a job is scheduled or running.

Open command prompt and enumerate the running deployments by executing this command:
stsadm -o enumsdeployments 

Now, we obtain the jobid and cancel this deployement as follows:
stsadm -o canceldeployment -id 2529c788-971c-46a3-b69f-a2a0a1fcc851
stsadm -o enumdeployments 
stsadm -o canceldeployment -id d9b076f0-ade0-4ea6-a271-2eaeec3fb6d3
remove-spsolution

Merge log file from All Server in SharePoint Farm

Merge-SPLogFile -Path "C:\Logs\FarmMergedLog.log" –Overwrite -Correlation “8121f15d-76c8-4b51-a1a7-a53811b11423”  -StartTime "07/07/2015 13:30:00" -EndTime "07/07/2015 13:52:00"

Farm Account Password change

STSADM.EXE -o updatefarmcredentials -userlogin asd\sdurairaj -password Welcome1

update link field value dynamically in infopath form

Link Field name in Design view

Set value Dynamically in code
XPathNavigator ipFormNav = MainDataSource.CreateNavigator();
           
XPathNavigator assnAttachURL = ipFormNav.SelectSingleNode("/my:myFields/my:URLPath", NamespaceManager);
XPathNavigator assnAttachDisplay = ipFormNav.SelectSingleNode("/my:myFields/my:URLPath/@my:URLDisplay", NamespaceManager);


assnAttachURL.SetValue("http://www.google.com");
assnAttachDisplay.SetValue("google");
Out put screen




Get Repeating table value into Datatable

DataTable dt = new DataTable();

XPathNavigator xpNav;
 XmlNamespaceManager nsMgr;
XmlDocument ipForm = null;
Stream formStream = null;

formStream = spfile_Flag.OpenBinaryStream();
 ipForm = new XmlDocument();
 ipForm.Load(formStream);
xpNav = ipForm.CreateNavigator();
 nsMgr = new XmlNamespaceManager(xpNav.NameTable);
 nsMgr.AddNamespace("my", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2014-10-16T17:16:01");
XPathNodeIterator baFormNodes = null;

                                string Products = string.Empty;
                                string Individual_Stock_IDs = string.Empty;
                                baFormNodes = xpNav.Select("/my:MembComm/my:ProductDetails/my:Itemwise", nsMgr);
                             
                                foreach (XPathNavigator baLine in baFormNodes)
                                {

                                    if (baLine.HasChildren)
                                    {
                                        dt.Rows.Add();

                                        baLine.MoveToFirstChild();
                                        Products = string.Empty;
                                        Products = baLine.Value;
                                        if (!string.IsNullOrEmpty(Products))
                                        {
                                            dt.Rows[rowcount]["Products"] = Products;
                                        }
                                        else
                                        {
                                            dt.Rows[rowcount]["Products"] = " ";
                                        }
                                        baLine.MoveToNext();
                                        Individual_Stock_IDs = string.Empty;
                                        Individual_Stock_IDs = baLine.Value;
                                        if (!string.IsNullOrEmpty(Individual_Stock_IDs))
                                        {
                                            dt.Rows[rowcount]["Individual Stock IDs"] = Individual_Stock_IDs;
                                        }
                                        else
                                        {
                                            dt.Rows[rowcount]["Individual Stock IDs"] = " ";
                                        }
                                       
                                        baLine.MoveToNext();
                                    }

                                }

Site Collection Administrator Report


#############################################

# Title: SiteCollectionAdministratorReport.ps1      
# Created By : Suresh Kumar Durairaj

#############################################

#region Addins
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null)            
{          
 Add-PSSnapin Microsoft.SharePoint.PowerShell          
}
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Publishing")
[System.Reflection.Assembly]::LoadWithPartialName("System")
[System.Reflection.Assembly]::LoadWithPartialName("System.IO")

#endregion

#region Log
$fileName = "SiteCollectionAdministratorReport"
$logdatetime=Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
$logFileName = $fileName +"_" +$logdatetime+ "_Log.txt"  
$invocation = (Get-Variable MyInvocation).Value
$directoryPath = Split-Path $invocation.MyCommand.Path

$logPath = $directoryPath + "\" + $logFileName
$CSVPath= $directoryPath + "\" +$fileName +"_" +$logdatetime+".csv"
$isLogFileCreated = $False  
 
function Write-Log([string]$logMsg)
{  
    if(!$isLogFileCreated){  
        Write-Host "Creating Log File..."  
        if(!(Test-Path -path $directoryPath))
        {
            Write-Host "Please Provide Proper Log Path" -ForegroundColor Red  
        }  
        else  
        {  
            $script:isLogFileCreated = $True  
            Write-Host "Log File ($logFileName) Created..."  
            [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)  
            Add-Content -Path $logPath -Value $logMessage  
        }  
    }  
    else  
    {  
        [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)  
        Add-Content -Path $logPath -Value $logMessage  
    }  
}  

#endregion


# Declare an array to collect our result objects
$resultsarray =@()

Get-SPSite | % {$_.RootWeb.SiteAdministrators} | select @{name='Url';expr={$_.ParentWeb.Url}}, LoginName, Email| Export-csv $CSVPath -notypeinformation


#region Remove addins
Remove-PsSnapin Microsoft.SharePoint.PowerShell
#endregion

Script that gets content databases sizes for all the web applications in a SharePoint Farm

############################################################################################################################################
# Script that gets content databases sizes for all the web applications in a SharePoint Farm
# Parameters: N/A
# Created By : Suresh Kumar Durairaj

############################################################################################################################################


If ((Get-PSSnapIn -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{ Add-PSSnapIn -Name Microsoft.SharePoint.PowerShell }

$host.Runspace.ThreadOptions = "ReuseThread"

#Function that gets the size of all the content databases
function Get-ContentDBSizes
{
    try
    {

        $spWebApps = Get-SPWebApplication -IncludeCentralAdministration
$ContentDatabaseInfo= "WebApp DisplayName" + "," + "WebApp Url"+ ","+ "WebApp Status"+ ","+ "ContentDatabase Name" + "," + "ContentDatabaseSize_in_GB"
$ContentDatabaseInfo
        foreach($spWebApp in $spWebApps)
        {
            #$spWebApp.Name
            $ContentDatabases = $spWebApp.ContentDatabases

            foreach($ContentDatabase in $ContentDatabases)
            {    

                $ContentDatabaseSize = [Math]::Round(($ContentDatabase.disksizerequired/1GB),2)
                $ContentDatabaseInfo = $spWebApp.DisplayName + "," + $spWebApp.Url+ ","+ $spWebApp.Status+ ","+$ContentDatabase.Name + "," + $ContentDatabaseSize + " GB"
                $ContentDatabaseInfo
                #Write-Host " * "  $spWebApp.DisplayName "-" $ContentDatabase.Name ": " $ContentDatabaseSize " GB"
            }
        }
    }
    catch [System.Exception]
    {
        write-host -f red $_.Exception.ToString()
    }
}


Start-SPAssignment –Global
Get-ContentDBSizes > PS_GetContentDBSizes.csv


Stop-SPAssignment –Global

Remove-PsSnapin Microsoft.SharePoint.PowerShell

Primary SiteCollection & seconday Owner Report


#############################################

# Title: SiteCollection_Primary & secondayOwner.ps1      
# Created By : Suresh Kumar Durairaj

#############################################

#region Addins
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null)            
{          
 Add-PSSnapin Microsoft.SharePoint.PowerShell          
}
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Publishing")
[System.Reflection.Assembly]::LoadWithPartialName("System")
[System.Reflection.Assembly]::LoadWithPartialName("System.IO")
[System.Enum]::GetNames("Microsoft.SharePoint.SPBasePermissions")

#endregion

#region Log
$fileName = "Primary_Secondary_sitecollectionOwner"
$logdatetime=Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
$logFileName = $fileName +"_" +$logdatetime+ "_Log.txt"  
$invocation = (Get-Variable MyInvocation).Value
$directoryPath = Split-Path $invocation.MyCommand.Path

$logPath = $directoryPath + "\" + $logFileName
$CSVPath= $directoryPath + "\" +$fileName +"_" +$logdatetime+".csv"
$isLogFileCreated = $False  
 
function Write-Log([string]$logMsg)
{  
    if(!$isLogFileCreated){  
        Write-Host "Creating Log File..."  
        if(!(Test-Path -path $directoryPath))
        {
            Write-Host "Please Provide Proper Log Path" -ForegroundColor Red  
        }  
        else  
        {  
            $script:isLogFileCreated = $True  
            Write-Host "Log File ($logFileName) Created..."  
            [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)  
            Add-Content -Path $logPath -Value $logMessage  
        }  
    }  
    else  
    {  
        [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)  
        Add-Content -Path $logPath -Value $logMessage  
    }  
}  

#endregion


# Declare an array to collect our result objects
$resultsarray =@()

Get-SPSite -Limit All | Select Url, Owner, SecondaryContact| Export-csv $CSVPath -notypeinformation

#region Remove addins
Remove-PsSnapin Microsoft.SharePoint.PowerShell
#endregion

Last Access Date or Last Modified Date


#############################################

# Title: LastModifiedDate.ps1      
# Created By : Suresh Kumar Durairaj
#############################################

#region Addins
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null)            
{          
 Add-PSSnapin Microsoft.SharePoint.PowerShell          
}
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Publishing")
[System.Reflection.Assembly]::LoadWithPartialName("System")
[System.Reflection.Assembly]::LoadWithPartialName("System.IO")

#endregion

#region Log
$fileName = "LastAccessDateScript"
$logdatetime=Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
$logFileName = $fileName +"_" +$logdatetime+ "_Log.txt"  
$invocation = (Get-Variable MyInvocation).Value
$directoryPath = Split-Path $invocation.MyCommand.Path

$logPath = $directoryPath + "\" + $logFileName
$CSVPath= $directoryPath + "\" +$fileName +"_" +$logdatetime+".csv"
$isLogFileCreated = $False  
 
function Write-Log([string]$logMsg)
{  
    if(!$isLogFileCreated){  
        Write-Host "Creating Log File..."  
        if(!(Test-Path -path $directoryPath))
        {
            Write-Host "Please Provide Proper Log Path" -ForegroundColor Red  
        }  
        else  
        {  
            $script:isLogFileCreated = $True  
            Write-Host "Log File ($logFileName) Created..."  
            [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)  
            Add-Content -Path $logPath -Value $logMessage  
        }  
    }  
    else  
    {  
        [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)  
        Add-Content -Path $logPath -Value $logMessage  
    }  
}  

#endregion


# Declare an array to collect our result objects
$resultsarray =@()


$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local
$farmWebServices = $farm.Services | where -FilterScript {$_.GetType() -eq [Microsoft.SharePoint.Administration.SPWebService]}
foreach ($farmWebService in $farmWebServices) {
  foreach ($webApplication in $farmWebService.WebApplications) {
Write-Log( "WebApplication Url:: "+ $webApplication.Name)
Write-Log("=======================================================")
    foreach ($site in $webApplication.Sites)
    {

$contactObject = new-object PSObject
$sitecollectionOwners=$null
$sitecollectionOwners = $site.RootWeb.SiteAdministrators
     $scas = ""
 if($sitecollectionOwners)
 {
     foreach ($siteAdmin in $sitecollectionOwners.Users)
     {
       $scas = $siteAdmin.LoginName + "; " + $scas
     }
 }
 if([string]::IsNullOrEmpty($scas) )
 {
  $scas=$site.Owner.Name
 }
#Logging the data
Write-Log( "Site Url:: "+ $site.Url)
Write-Log( "Site Owner::" + $scas)
        Write-Log( "Modified Date::"+ $site.LastContentModifiedDate)



        # Add our data to $contactObject as attributes using the add-member commandlet
$contactObject | add-member -membertype NoteProperty -name "Site Url" -Value $site.Url
$contactObject | add-member -membertype NoteProperty -name "Site Owner" -Value $scas
$contactObject | add-member -membertype NoteProperty -name "Modified Date" -Value $site.LastContentModifiedDate
$resultsarray += $contactObject    
 

 if($site.AllWebs.Count -gt 0)
 {
 foreach ($subsite in $site.AllWebs)
     {
  $siteowner=""
           $siteOwners = $subsite.AssociatedOwnerGroup
           if($siteOwners)
           {
               foreach ($owner in $subsite.Users)
               {

$siteowner=$owner.Name+";"+$siteowner

               }
           }
 if([string]::IsNullOrEmpty($siteowner) )
 {
  $siteowner=$site.Owner.Name
 }

#Logging the data
Write-Log( "Site Url:: "+ $site.Url)
Write-Log( "Site Owner" + $scas)
       Write-Log( "Modified Date"+ $site.LastContentModifiedDate)

$contactObject = new-object PSObject
         
# Add our data to $contactObject as attributes using the add-member commandlet
$contactObject | add-member -membertype NoteProperty -name "Site Url" -Value $subsite.Url
$contactObject | add-member -membertype NoteProperty -name "Site Owner" -Value $siteowner
$contactObject | add-member -membertype NoteProperty -name "Modified Date" -Value $subsite.LastItemModifiedDate
# Save the current $contactObject by appending it to $resultsArray ( += means append a new element to ‘me’)
$resultsarray += $contactObject                      

 }


 }



 $resultsarray| Export-csv $CSVPath -notypeinformation
      $site.Dispose()
Write-Log("=======================================================")
    }
  }
}

#region Remove addins
Remove-PsSnapin Microsoft.SharePoint.PowerShell
#endregion