Sunday, October 16, 2016

SharePoint Solution (WSP) management using PowerShell


My recommended approach to manage SharePoint WSP solutions is; Powershell instead of GUI approach using SharePoint administration. Despite that, you can use the Central Administration to do that.
Open SharePoint Powershell or windows Powershell using ‘Run as administrator’.
If you open windows default Powershell , you need to load the SharePoint snap in explicitly, it auto loads in case of SharePoint Powershell.


PS C:\Windows\system32> add-pssnapin Microsoft.Sharepoint.Powershell



We will see some important Powershell cmdlet which are useful for solution management. (This article will be mainly focused on main parameters available with cmdlets, for all parameter details, please refer to Ms technet https://technet.microsoft.com/EN-US/library/ee906565.aspx.


Add-SPSolution


Add-SpSolution -LiteralPath [path of the wsp file with name and extension]


Add a SharePoint WSP solution to the Farm.


Build your solution in visual studio, ->Publish to a folder. You will find a WSP file named with your solution name. For example, it is ‘MyCore.Aritifacts.wsp’.


Let’s add this solution.




Please check the solution has been added but not deployed yet.


Install-SPSolution


This cmdlet deploys the installed sharepoint solution to the farm.


PS> Install-SPSolution -Identity nameOfTheSolution.wsp -GACDeployment -CompatibilityLevel 15
PS> Install-SPSolution -Identity nameOfTheSolution.wsp -GACDeployment -CompatibilityLevel {14,15}


This deploys solution to the farm and tells for the GAC deployment if required.
-CompatibilityLevel parameter is optional and following are the values which can be used with that.


Value
Result
14
Installs solution to 14 directories only
15
Installs solution to 15 directories only
“14,15”
Installs solution to both 14 and 15 directories
“AllVersions” or “All”
Installs solution to both 14 and 15 directories
“OldVersions” or “Old”
Installs solution to 14 directories only
“NewVersion” or “New”
Installs solution to 15 directories only




This deploys the solution to the farm, please check the snap shot of the SharePoint central admin- > solution management.


It is globally deployed. It means deployed to all the servers in the Farm. You can now activate the feature at Site Collection level depending on the scope of the feature.


Remove-SPSolution
Before you remove any deployed solution from the farm, you need to make sure that it has been retracted from the farm.


To retract the deployed solution, Remove-SPSolution is used as following. This is like preparation to completely uninstall a solution from entire SP Farm.


PS> Uninstall-SPSolution -Identity nameOfTheSolution.wsp


You can use the CompatabilityLevel parameter like we used in Install-SPSolution.


Cmdlet will ask if you are sure to complete the operation. Type “Y” if you are share to uninstall the solution.
The Admin panel shall look like following now.
This says the solution is not yet completely retracted.
After some time, it shall look like the following.
Solution “Not Deployed”.
Now are are ready to remove the solution completely from the Farm.


Remove-SPSolution
This command removed the solution from the SP Farm.


PS> Remove-SPSolution -Identity nameOfTheSolution.wps




This will again ask you for the confirmation, press “Y” if you are sure to delete. Once you press “Y”. This SP will start the removal of Solution from the Farm.


Check with in few seconds (depending on the size of the solution), refresh the solution management page in Administration and you will find the solution no more exists in the Farm.


Before I end the article there are some very crucial tips which you can use with the above command.
The Powershell in some scenarios will not allow your operations, for example, if the solution is being deployed on the farm, your uninstall command will not be accepted. If the solution is being retracted from the farm, you remove solution command will not be accepted. For real scenarios, I would encourage you to handle all these exceptions using the Powershell commands.


I am trying to install my solution on the Farm


Now immediately I tried to uninstall the Solution. Following is the screenshot of the error.

This throws an exception describing 'the solution can’t be retracted at the moment as it already under deployment or retraction'. In our case it is under deployment. In the same way if the solution is being retracted and you are trying to remove it shall through similar exception. I recommend to handle this in Powershell script like following. The screenshot below checks it the solution exists and is deployed to the Farm. After this verification only it commands to uninstall the Solution. Below the screenshot, I will provide the cmdlet as well.



PS> $spSolName = "yourSolutionName.wsp"
PS> $mySol = Get-SPSolution | where-object { $_.Name -eq $spSolName}
PS> $mySol


Name                           SolutionId                           Deployed
----                           ----------                           --------
yourSolutionName.wsp        797a6dd5-352c-418a-8ec6-2fb55c6740d7 True


PS> if($mySol -ne $null) { if($mySol.Deployed -eq $true) { uninstall-s
psolution -identity $mySol  }  }


Confirm
Are you sure you want to perform this action?
Performing the operation "Uninstall-SPSolution" on target "yourSolutionName.wsp".
[Y] Yes  [A] Yes to All  [N] No  [L] No to All  [S] Suspend  [?] Help
(default is "Y"):Y


I am sure, now you have an idea how powerfully we can use the Powershell cmdlet for the basic operation. I would encourage you to prepare the script file for these operations. This was just an example to handle exception during uninstall, you can similarly handle exception for remove and other cmdlets.
You can similarly add a while loop in powershell to wait unless the Solution is ready to be installed/uninstalled etc.


while ($mySol.Deployed -eq $true)
       {
           Write-Host -NoNewLine
           Start-Sleep -Seconds 2
       }




I simply used the command in my already opened prompt (where I already have values for variable stored).
It just stopped after the first line (sleeps for 2 seconds before looping). Then I manually started the retraction of the solution from the Solution Management in Admin Panel. Once the solution status came to “Not Deployed”, then the command finished and went to the next line. Now you can understand how crucial are these cmdlets during Live scenarios of Solution Management in a Farm.


Keep Learning…...


Sunday, September 18, 2016

SharePoint PowerShell - BackUps and Restore

SharePoint: PowerShell - BackUps and Restore

Open Windows PowerShell using Run as admin
PC> add-pssnapin Microsoft.sharepoint.powershell

BackUp & Restore in SharePoint 2013

In SharePoint 2013, you can use Windows PowerShell functionality to perform a backup or restore process for the following items:
  • Farm
  • Site collection
  • Configuration database
  • Services
  • List or document


Farm BackUp
Syntax:
Backup-SPFarm -BackupMethod -Directory [-AssignmentCollection ] [-BackupThreads ] [-ConfigurationOnly ] [-Confirm []] [-Force ] [-Item ] [-Percentage ] [-WhatIf []]

Another Syntax(This doesn’t backups actually, it shows the items to be backed up in this command):

Backup-SPFarm -ShowTree [-AssignmentCollection ] [-ConfigurationOnly ] [-Confirm []] [-Item ] [-WhatIf []]

Example:
PS C:\Windows\system32> backup-spfarm -directory \\KSSHRPT01\FarmBackUp -backupmethod full
PS C:\Windows\system32> backup-spfarm -directory \\KSSHRPT01\FarmBackUp -backupmethod full -ConfigurationOnly

*The shared path shall be accessible from all the server. You can use local PC path in case if you have single server farm and have both SP and DB are installed on the same machine.




BackUp a Site collection
Syntax:
Backup-SPSite [-Identity] -Path [-AssignmentCollection ] [-Confirm []] [-Force ] [-NoSiteLock ] [-UseSqlSnapshot ] [-WhatIf []]

PS C:\Users\spadmin> $s = "http://ksshrpt01"
PS C:\Users\spadmin> $pth = "C:\KS\SiteBackUps\Primarysite.bak"
PS C:\Users\spadmin> backup-spsite $s $pth
PS C:\Users\spadmin> backup-spsite $s -path  $pth

Another way to do the same:

PS C:\Users\spadmin> get-spsiteadministration $s | Backup-spsite -path $pth

PS C:\Users\spadmin> backup-spsite $s -path  $pth -usesqlsnapshot -force
This example backs up a site collection using database snapshots to ensure backup integrity.Specifies a SQL Database Snapshot will be created when the backup begins, and all site collection data will be retrieved directly from the database snapshot. This snapshot will be deleted automatically when the backup completes
The UseSqlSnapshot parameter is recommended if the database server hosting your content database supports database snapshots such as SQL Server Enterprise Edition and SQL Server Developer Edition. This is because it will ensure a valid backup while allowing users to continue reading and writing to the site collection during the backup. It is not necessary to specify the NoSiteLock parameter when specifying the UseSqlSnapshot parameter.

PS C:\Windows\system32> backup-spfarm -showtree -item "Microsoft sharepoint foundation web application" -verbose
*Gives the tree path of back procedure, but doesn’t actually backs up the Farm.

PS C:\Windows\system32>Backup-SPFarm -Directory C:\Backup -BackupMethod full -BackupThreads 10 -Force
This example performs a backup of a farm using 10 threads and forces the backup to be saved to the C:\Backup directory even though SharePoint estimates that it does not have sufficient space available.







Backup-SPConfigurationDatabase
Performs a farm-level configuration-only backup.

Syntax:

Backup-SPConfigurationDatabase -Directory [-AssignmentCollection ] [-DatabaseCredentials ] [-DatabaseName ] [-DatabaseServer ] [-Item ]

Backup-SPConfigurationDatabase -ShowTree [-AssignmentCollection ] [-DatabaseCredentials ] [-DatabaseName ] [-DatabaseServer ] [-Item ]


The Backup-SPConfigurationDatabase cmdlet performs a configuration-only backup of the current farm or a configuration-only backup of a separate configuration database which is not attached to the current farm. If you wish to perform a configuration-only backup of the current farm, there is no need to specify the DatabaseServer and DatabaseName parameters. However, using the Backup-SPFarm cmdlet with the ConfigurationOnly parameter is recommended for such a scenario.
An example of a configuration backup is an administrator creates a farm configuration template which then can be applied to other SharePoint farms by performing a restore using the Restore-SPFarm cmdlet.

PS>Backup-SPConfigurationDatabase -DatabaseName SharePoint_Config -DatabaseServer SqlServer1 -Directory \\server\share\Backup -ShowTree

This example displays components that are available for inclusion in a configuration-only backup.

PS>Backup-SPConfigurationDatabase -DatabaseName SharePoint_Config -DatabaseServer SqlServer1 -Directory \\server\share\Backup -Verbose
This example performs a configuration-only backup with verbose output.





Get-SPBackupHistory

Returns a history of backup and restore operations.
The Get-SPBackupHistory cmdlet reads a history of backup and restore operations that have been run. Specifies whether you want to display only the backup history, only the restore history, or all of the history.

Syntax:
Get-SPBackupHistory -Directory [-AssignmentCollection ] [-ShowBackup ] [-ShowRestore ]




PS C:\Windows\system32> Get-SPBackupHistory -Directory \\KSSHRPT01\FarmBackUp

T S Operation ID                         Method    Start Time
- - ------------                         ------    ----------
B Y 3682c4c6-7eb8-4f61-9714-9870e67d9948 Full


PS C:\Windows\system32>


PS C:\Windows\system32>Get-SPBackupHistory -Directory C:\Backup -ShowBackup
This example returns all of the farm backup operations that have been run for the C:\Backup directory.

PS C:\Windows\system32>(Get-SPBackupHistory -Directory C:\Backup -ShowBackup)[0].SelfId | Restore-SPFarm -Directory C:\Backup -RestoreMethod overwrite

This example gets all of the farm backup operations that have been run for the "C:\Backup" directory, finds the most recent backup, and then passes its backup GUID to the Restore-SPFarm cmdlet. The Restore-SPFarm cmdlet will then perform an overwrite restore from that backup package.

Restore-SPFarm
Restores one or more items from a backup.

This cmdlet contains more than one parameter set. You may only use parameters from one parameter set, and you may not combine parameters from different parameter sets. For more information about how to use parameter sets, see Cmdlet Parameter Sets.
The Restore-SPFarm cmdlet restores one or more items from a backup such as an individual database, Web application, or the entire farm. This cmdlet can also be used to apply a farm template to the entire farm.


Syntax:
Restore-SPFarm -Directory -RestoreMethod [-AssignmentCollection ] [-BackupId ] [-ConfigurationOnly ] [-Confirm []] [-FarmCredentials ] [-Force ] [-Item ] [-NewDatabaseServer ] [-Percentage ] [-RestoreThreads ] [-WhatIf []]

Restore-SPFarm -Directory -ShowTree [-AssignmentCollection ] [-BackupId ] [-ConfigurationOnly ] [-Confirm []] [-Item ] [-WhatIf []]

Example:

PS>Restore-SPFarm -Directory \\file_server\share\Backup -BackupId 12345678-90ab-cdef-1234-567890abcdef -RestoreMethod new -ConfigurationOnly

This example restores the configuration settings from the backup package in the \\file_server\share\Backup directory to the farm.

PS>Restore-SPFarm -ShowTree -Directory \\file_server\share\Backup -BackupId 12345678-90ab-cdef-1234-567890abcdef -Item "Microsoft SharePoint Foundation Web Application" -Verbose

This example show which components of the farm would be restored under the Microsoft SharePoint Foundation Web Application node, but does not actually restore them.

PS>Restore-SPFarm -Directory C:\Backup -BackupId 12345678-90ab-cdef-1234-567890abcdef  -RestoreMethod overwrite -RestoreThreads 10 -Force

This example restores a farm by using 10 threads and suppresses the overwrite warning.

Restore-SPSite
Restores a site collection.
The Restore-SPSite cmdlet performs a restoration of the site collection to a location specified by the Identity parameter. A content database may only contain one copy of a site collection. If a site collection is backed up and restored to a different URL location within the same Web application, an additional content database must be available to hold the restored copy of the site collection.

Example:

PS>Restore-SPSite http://server_name/sites/site_name -Path C:\Backup\site_name.bak

This example restores a site collection from the backup file C:\Backup\site_name.bak to the site collection URL http://server_name/sites/site_name.

PS>Restore-SPSite http://server_name/sites/site_name -Path C:\Backup\site_name.bak -Force -DatabaseServer SQLBE1 -DatabaseName SQLDB1

This example restores a site collection backup from the backup file
C:\Backup\site_name.bak, but overwrites the existing site collection at http://server_name/sites/site_name while specifying that the site collection must be stored in a specific content database.

PS>Restore-SPSite http://www.example.com -Path \\file_server\share\site_name.bak -HostHeaderWebApplication http://server_name

This example restores a site collection backup from the backup file \\file_server\share\site_name.bak to the host-named site collection http://www.example.com on the Web application http://server_name.


Reference: MSDN

SharePoint PowerShell to Manage Term Store / Add Terms using PowerShell

SharePoint PowerShell to Manage Term Store / Add Terms


//get the term store
$mysite = get-spsite “http://yoursite:portnumber
$taxonomySession = get-taxonomySession -site $mysite
$termStore = $taxonomySession.TermStores[“Managed Metadata Service”]


//now we will create the Term Store groups. Before we create any group we will check if the group already exists
Example 1:


if($termstore.groups["News Keys"] -eq $null) { $termstoregroup = $termstore.creategroup("News Keys");  $termstore.description = "News Group";  $termstore.addgroupmanager ("KS\spadmin"); $termstore.addcontributor ("ks\k.singh");$termStore.CommitAll();}


This is not working as “description” is not an identified property.


Example 2:


if($termstore.groups["Main News Keys"] -eq $null) { echo "group is not there";  echo "group is there"; $termstoregroup = $termstore.creategroup("Main News Keys"); $termstore.commitall();   }

Example 3:
$session = Get-SPTaxonomySession -Site "http://ksshrpt01/";
$termStore = $session.TermStores[“Managed Metadata Service”];
$group = $termstore.CreateGroup(“News Group”);
$group.Description = "My News Group";
$termStore.addgroupmanager ("KS\spadmin");
$termStore.CommitAll();
$termSet = $group.CreateTermSet(“Sports”,1033);
$termSet.Description = “Sports”;
$termSet.IsAvailableForTagging = $true;
$termSet.IsOpenForTermCreation = $true;
$termStore.CommitAll();


I encountered many issues/errors and finally went through. I will advise the following troubleshooting tips.


  1. termstore.description("") - Invalid command. This never worked for me. I shall update this once I come across any solution to this. Remove this cmdlet if you too face the same issue.
  2. I faced issue related to Permission (UnAuthorized User). I started the PowerShell console as Administrator and still I had the same issue.
  3. Central Admin -> Manage Service applications -> Managed Metadata Service -> Select and go to permission. Assign permission to the user running PowerShell.
  4. Central Admin -> Service Applications->Managed Metadata Service -> Properties -> Set term store administrator as the user you want. Save it and reset IIS as a precautionary measure.


The Create TermStore Group command shall now work for you.



Both of the following commands worked well.


  1. PS> if($termstore.groups["Main News Keys"] -eq $null) { echo "group is not there";  $termstoregroup = $termstore.creategroup("Main News Keys");  $termstore.commitall();   }
  2. PS>$session = Get-SPTaxonomySession -Site "http://ksshrpt01/";
PS>$termStore = $session.TermStores[“Managed Metadata Service”];
PS>$group = $termstore.CreateGroup(“News Group”);
PS>$group.Description = "My News Group";
PS>$termStore.CommitAll();


*We will use the second command for all further examples

Please check the following screen.


Use following the command to assign permission to the group.


PS> $termstoregroup.addGroupManager("ks\spadmin")
PS> $termstoregroup.AddContributor("ks\k.singh")


You need to commit the changes to the Term Store.


PS>$termStore.CommitAll();


Let’s create Term Sets in the Term Store

PS> $newTermSet = $termstoregroup.CreateTermSet("Sports",1033)
PS> $newTermSet = $termstoregroup.CreateTermSet("Politics",1033)
PS C:\Users\spadmin> $newTermSet = $termstoregroup.CreateTermSet("Nation",1033)
PS C:\Users\spadmin> $newTermSet = $termstoregroup.CreateTermSet("Business",1033)
PS C:\Users\spadmin> $termstore.commitall()



Hope this helps…..

Visual Studio Build Error - The "GenerateResource" task failed unexpectedly

Error: "The GenerateResource task failed unexpectedly" This error is quite common while building the project in Visual Studio....