Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.
Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Monday, April 11, 2016

Powershell Script to Install a DLL into GAC on Windows Server 2012/ Windows Server 2012 R2 OS when there is no Visual Studio Installed on Web Server



Set-location "DLL Source Path"           
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")           
$publish = New-Object System.EnterpriseServices.Internal.Publish           
$publish.GacInstall("DLL Source Path\FileName.dll")           
iisreset

Example for Source Paths:-
            C:\DLLS

Thursday, October 01, 2015

PowerShell for Error: The trust relationship between this workstation and the primary domain failed in Windows Server 2012


I got this in one of my Hyper-V VM's. I logged in with my computer name\Administrator into the server and the below script had fixed the issue.

Reset-ComputerMachinePassword -Server Domain Controller with FQDN Name -Credential DomainName\ADMINISTRATOR

Wednesday, December 14, 2011

Powershell Scripts for SharePoint

Backup and Restore in SharePoint 2010 using PowerShell

It is essential to have proper backup/restore strategy in place for your SharePoint farms. SharePoint 2010 provides three types of tools for backup/restore for your server farm. The tools are
Central Administration
Windows PowerShell
Stsadm.exe
You need to carefully decide what you are going to backing up and where you are storing these backups. Be noted that SharePoint 2010 doesn’t provide a method to backup directly to tape. SharePoint 2010 backs up to a UNC file share. Technically UNC file share can be anywhere, but it is recommended that you take your backup to a UNC file share in your LAN.
Let me explore each tool available for backup.
Central Administration: You cannot schedule a backup via Central Administration. The primary use of Central Administration backups is to verify the configuration of the target backup location and to back up server farms before major operations. It is recommended to take backup using Central Administration, once you create all web applications and site collections required by your server farm. Also take one backup using Central Administration before any major upgrade of the farm.
Windows PowerShell: The preferred way to take backups in SharePoint Server 2010 is by using windows PowerShell. This method gives you the most options and will be fully supported in the future. You can also schedule the backup using Windows PowerShell.
Stsadm.exe: Stsadm was the command line administration tool available for SharePoint 2007. SharePoint 2010 also provides Stsadm, but it is recommended to use PowerShell as Stsadm is there to offer backward compatibility. Many of the Stsadm commands implemented in SharePoint Server 2010 existed in SharePoint Server 2007. Configuring command-line backups using Stsadm is easy, but it is limited to basic farm backup functionality
In this article I am going to demonstrate the PowerShell commandlets to take various types of backup from SharePoint 2010.
First you need to decide, where you are going to store the backups. Make a UNC share for that location. In order to back up to file share, the following accounts need full permissions to the backup location.
  1. SQL Server service account
  2. SharePoint 2010 Timer Log On account
  3. User account, who is executing the command.
Also you have to ensure that you have enough disk space available for the backup. In the remaining section of this article details the various backup options available to you.

Farm Backup

To back up a server farm using Windows PowerShell, you can use Backup-SPFarm command. The syntax of the command is as follows.
Backup-SPFarm -directory <UNC File Share> -BackupMethod <Full | Differential>
The Backup-SPFarm supports the following options
  • Directory - Defines the backup location previously prepared.
  • BackupThreads - The default thread count is 3. Increasing the thread count will result in faster backup, but it will affect the server performance during backup. Also increasing the threads will make it difficult to check backup logs.
  • ShowTree - Displays the objects in the farm those are available to be backed up. If you use this setting in conjunction with Item, it is scoped to the object underneath Item.
  • ConfigurationOnly – This option specifies to backup only the farm configuration data. No content will be backed up when you specify ConfigurationOnly in the command.
  • Item – You can back up a farm component—such as a Web application, content database, or service application—using the Item parameter. You cannot back up site collections, sites, list, libraries, or list items using the Item parameter.
  • Percentage - You can specify the progress increments on the screen. If scripting, you do not need to use the Percentage option.
  • Force - Using force will bypass the default behavior of halting the backup if the estimator calculates there is insufficient disk space.
  • Verbose – This option will display the progress of the backup in the command line. If this is not presented, you won’t be presented with current progress information.
  • WhatIf - This is a common PowerShell feature, if you specify this option, the command will display the output of running the backup without actually performing the backup.

Restore a Server Farm

The backups taken by PowerShell can be restored by Central Administration. Also it is possible to restore the farm using the PowerShell Script. To restore a farm from backup you can use Restore-SPFarm commandlet.
The UNC share where you configured your backup, may contains more than one backup. So the PowerShell command for restore requires you to specify the backup ID for the backup to restore. No problem, there is a command available to list all the backups available under a UNC share. The command is as follows.
Get-SPBackupHistory -Directory <Backup folder> -ShowBackup [-Verbose]
See the output of the command.
clip_image002
There is another way to find the backup ID, in the root folder of the UNC share used for backup; you can find an xml file named spbrtoc.xml (SharePoint Backup Restore Table Of Contents). To find the ID, open the UNC share in windows explorer, open the spbrtoc.xml in any text editor (e.g. notepad) and you can find all backups with IDs]
The syntax for Restore-SPFarm command is as follows
Restore-SPFarm -Directory UNCShare -BackupId <id of backup>
The Restore-SPFarm supports the following options.
  • Directory - specifies the path to the SharePoint Server 2010 backup location you want to restore from. There must be a valid spbrtoc.xml file in the root of the backup directory.
  • RestoreMethod – Either New or Overwrite. The New option restores the selected backup components and configuration using either new database names or a new SQL Server instance, or both. The Overwrite option restores the content and configuration to the same database instances.
  • BackupId - The unique backup ID you want to restore.
  • ConfigurationOnly - Restores only the farm configuration data, it will not restore any content.
  • Confirm - Requires you to confirm the backup by typing Y, it is just a precautionary option.
  • FarmCredentials - You must supply the farm credentials when restoring content and configuration data.
  • Force – if you want to restore to the existing farm, use this option.
  • Item - Indicates the part of the backup you want to restore. For example, if you have performed a full farm backup, you might choose to only restore a Web application or content database.
  • NewDatabaseServer - If you want to restore to an alternate database server, you can specify that during the restore process.
  • Percentage - You can specify the progress increments on the screen. Percentage complete is seen only when using the Verbose option.
  • RestoreThreads - The default number of process threads is 3. This can be increased to 10 or decreased to 1.
  • WhatIf - Displays the effect of a command without running an actual restore process.
  • Verbose - Displays the output of a command.

Backup web applications using PowerShell

You can use the –item option to the Backup-SPFarm command to back up a particular component in a farm. By specifying the item option with the Backup-SPFarm command, you can backup a web application, a service application or a content database. Also using the Restore-SPFarm command, you can restore any of these.
You can also restore individual items from a full back up without restoring the entire farm backup. So if you are taking full farm backup, it is not necessary to take item wise backups separately.
In order to backup an item, you need to specify the item name you need to backup. To retrieve the item names for backing up, you can use the following command.
Backup-SPFarm –showtree
This command will list the hierarchical items available in the farm. You can retrieve the item name by following the command output.
See the output of the command
clip_image003
To backup a particular item, you can
Backup-spfarm –directory <uncpath> -item “Hierarchical item name” –backupmethod FULL |Differential
e.g.:
Backup-spfarm –directory \\ServerName\UNCShare -item “Farm\ Microsoft SharePoint Foundation Web Application\SharePoint - 2038” –backupmethod FULL
Similarly you can Restore a particular item from a farm backup. See the sample command
Restore-SPFarm –directory <uncpath> -backupid <backup id> -item <item to be backed up>

Backup Site Collection

Sharepoint 2010 supports granular backup and restore. You can backup/restore site collections, individual sites and lists. In this section I am going to cover only the site collection backup.
Windows PowerShell will automatically lock the site collection during backup to reduce the risk of SQL blocking and locking errors. Also it is possible to backup site collection using a SQL snapshot to back up the data. To backup site collections you can use the command Backup-SPSite. The following are the options available for Backup-SPSite.
  • Identity - specifies the URL or GUID of the site collection to back up
  • Path -The full backup path, including the file name.  Here you can use the file path, it is not necessary to specify the UNC path here. 
  • Confirm - Requires you to confirm the backup by typing Y.
  • Force - If you want to overwrite an existing back up file, use the Force option.
  • NoSiteLock - If you want to back up the site collection without making it read-only, use the NoSiteLock option. If you are taking large site collection backups, without a site lock, the back up may fail.
  • UseSqlSnapshot - If you need to back up site collections during the day and require users to continue full read/write operations, you’ll need to create a SQL snapshot to back up from. Using this option creates a temporary SQL Server database snapshot. After the snapshot is created, the backup will be from the snapshot, not the live database. This is the best method to get a full fidelity site collection backup.
  • WhatIf Shows the effects of a command without performing the actual backup
E.G.: Backup-spsite –identity http://win-hgdsnnuakhv/sites/testsite -path c:\sitebkup\mysite.bak

Schedule backups

Once the server farm is up and running, you need to take regular backups. You need to automate the server backup procedure. You need to decide your backup plan. This depends on your farm. You need to carefully decide the backup plan. Also test your back up by restoring it to a test environment, for making sure you are ready for disaster recovery.
Providing a recommendation for backup farm is depends on the implementation. Recently I worked with a farm, where I have 3 site collections in 3 different web applications. I have decided the following backup sets.
  1. Monthly full backup for the entire server farm
  2. Weekly differential backup for the entire server farm
  3. Weekly full backup for each site collection
  4. Daily differential backup for each site collection
Make sure you are taking the decision by carefully considering your back up plans.
Next you need to schedule the scripts. You need to do the following tasks for scheduling the back up.
  1. Create a .ps1 file with your PowerShell commands
  2. Create a batch file that calls the ps1 file
  3. Configure the batch file to execute in certain interval.
The following steps demonstrate scheduling a full farm backup using PowerShell. First create a Windows PowerShell script file with the following contents.
Add-PSSnapin Microsoft.SharePoint.PowerShell
Backup-SPFarm -directory \\win-hgdsnnuakhv\farmbkup -backupmethod FULL
Save this file with extension .ps1. I have named the file as farmfullbkup.ps1.
Now create a batch file, which calls this PowerShell Script. The batch file content is as follows.
PowerShell -command C:\BackupScheduleScripts\FarmFullBkup.ps1
Save this file with extension .bat. In my case, I named the file as FarmFullBkup.bat
Now you can schedule this batch file as you required using Windows task scheduler. In my case I configured this to execute once in a month.

Conclusion

SharePoint provides lot of options for backup/ restore, from a full farm level to list level. Planning for backup / restore in very important in any server farm and you need to carefully decide what backup / restore strategy will help you.


Published
Wednesday, May 18, 2011 1:44 PM
by
sreejukg


Monday, December 05, 2011

Adding a content database using PowerShell in SharePoint 2010

Adding a content database using PowerShell in SharePoint 2010
To attach an existing content database:

Mount-SPContentDatabase "<ContentDb>" –DatabaseServer "<DbServer>"
–WebApplication http://WebapplicationName

<ContentDb> is the content database to be attached.

<DbServer> is the name of the database server.

http://WebapplicationName is the name of the Web application to which
the content database is being attached.

To detach a content database:

Dismount-SPContentDatabase "<ContentdBName>"

Where is the name of the content database.

How to list all the commands in PowerShell ?

Get-Command * commands gets you all the Powershell commands.

Permissions for Windows PowerShell - SPShellAdmin

Permissions for Windows PowerShell - SPShellAdmin
In order to use Windows PowerShell for SharePoint 2010 Products, a
user must be a member of the SharePoint_Shell_Access role on the
configuration and content database. In addition to this, the user must
also be a member of the WSS_ADMIN_WPG local group on the computer
where SharePoint 2010 Products is installed.

To add a user as SharePoint_Shell_Access on the SharePoint database
use the below powershell cmdlet :

Add-SPShellAdmin

Please Note that to run the above cmdlet you must have
* Membership in the securityadmin fixed server role on the SQL Server instance
* Membership in the db_owner fixed database role on all affected databases
* and local administrative permission on the local computer.

In addition to above some important things to Note:

* The user gets added to the WSS_Admin_WPG group on all Web servers
when the user is added to the SharePoint_Shell_Access role.

* If the target database does not have a SharePoint_Shell_Access role,
the role is automatically created.

* If you use the database parameter, the user is added to the role on
the farm configuration database, the Central Administration content
database, and the specified database. Using the database parameter is
the preferred method because most of the administrative operations
require access to the Central Administration content database. The
cmdlet is something like below :

Add-SPShellAdmin -UserName Domainname\User -database {Database GUID}

If you need going to install a webpart or any custom solution in SharePoint 2010 using PowerShell What permissions do you need?

If you need going to install a webpart or any custom solution in SharePoint 2010 using PowerShell What permissions do you need?
In order to use Windows PowerShell for SharePoint 2010 Products, a user must be a member of the SharePoint_Shell_Access role on the configuration and content database. In addition to this, the user must
also be a member of the WSS_ADMIN_WPG local group on the computer where SharePoint 2010 Products is installed.

Where is Powershell located in sharePoint ?

On the Start menu, click All Programs -> Click Microsoft SharePoint 2010 Products -> Click SharePoint 2010 Management Shell.

Can you Create PowerShell scripts for deploying components in SharePoint ?

If you are creating a webpart with VS 2010 then you can deploy it using ctrl + f5. However, to activate the webpart feature you can write a powershell script (.ps1) and execute it after dpeloyment.

What are CMDLets?

Windows PowerShell introduces the concept of a cmdlet which are simple build in commands, written in a .net language like C# or VB.

How is Windows Powershell different from Stsadm ?

Unlike stsadm, which accept and return text, Windows PowerShell is built on the Microsoft .NET Framework and accepts and returns .NET Framework objects. In addition to that it also gives you access to the file system on the computer so that you can access registry,digital signature certificate etc..

What is windows PowerShell?

Windows PowerShell is a new Windows command-line shell designed especially for system administrators. In the SharePoint administration context, Windows PowerShell is another administration tool that supersedes the existing Stsadm.exe.

SharePoint 2010 Windows PowerShell Commands Part2

Some more PowerShell Commands

Site Collection Commands

Create Site Collection :

Get-SPWebTemplate
$template = Get-SPWebTemplate "STS#0"
New-SPSite -Url "" -OwnerAlias "" -Template $template

Delete Site Collection :

Remove-SPSite -Identity "URL of site Collection" -GradualDelete

Change Site collection Quotas :
Set-SPSite -Identity "SiteCollection Url" -MaxSize Quota

Add site Collection Administrators :


Set-SPSite -Identity "" -SecondaryOwnerAlias ""

Lock or unlock a site collection :

Set-SPSite -Identity "Site Collection Url" -LockState ""

is one of the following vales :

# Unlock: To unlock the site collection and make it available to users.

# NoAdditions: To prevent users from adding new content to the site collection. Updates and deletions are still allowed.

# ReadOnly: To prevent users from adding, updating, or deleting content.

# NoAccess: To prevent access to content completely. Users who attempt to access the site receive an access-denied message.

Create a site :


New-SPSite "http://sitecollection/sites/Subsite -OwnerAlias "DOMAIN\UserName" –Language 1033

SharePoint 2010 Windows PowerShell Commands - Part1

To Open the Windows PowerShell Session :

1. On the Start menu, click All Programs.

2. Click Microsoft SharePoint 2010 Products.

3. Click SharePoint 2010 Management Shell

Note : You should have SharePoint_Shell_Access role on the configuration database and you should be a member of the WSS_ADMIN_WPG local group on the computer where SharePoint Server 2010 is installed.


Some of the Common Commands and Operations are:


Create Web Application Variable

$webapp = Get-SPWebApplication "http://WebapplicationUrl"


Create SharePoint Site Variable (Instance of SPSite)

$siteurl = "http://MySharePointSite"

$Oursite=new-object Microsoft.SharePoint.SPSite($siteurl)

Here we have created a variable Oursite, which contains an instance of type SPSite. Now you can use it to display all webs in the site collection.

$Oursite.AllWebs more // List all Webs in the Site


Create Service Application Variable

$spapp = Get-SPServiceApplication -Name "ServiceApplicationDisplayName"


Create a Webapplication:

New -SPWebApplication -ApplicationPoolName <Name of the application pool> -Name <Name of the new Web application> [ -Port <Port on which the Web application can be accessed>] [-HostHeader <Valid URL assigned to the Web application that must correlate to the alternate access mapping configuration>] [-URL <Load-balanced URL for the Web application>][ -ApplicationPoolAccount <User account that this application pool will run as>]

Delete WebApplication


Remove-SPWebApplication –identity -URL <http://sitename> -Confirm


Create\Delete a Site Collection:


Create a Site collection:

Get-SPWebTemplate

$template = Get-SPWebTemplate "STS#0"

New-SPSite –Url "<URL for the new site collection>" –OwnerAlias "<domain\user>" –Template $template

Here $template is a Variable to store the type of template we want to use while creating a site collection.

Delete a Site Collection:

Remove-SPSite –Identity <URL> –GradualDelete

Here <URL > is a site Collection Url .



Back\Restore a content database

To Backup :

Backup -SPFarm -Directory <Backup folder> -BackupMethod -Item <Content database name> [-Verbose]

Backup folder - is a folder to save your backup.

BackupMethod – Can Specify between Full or Differential.


To Restore:

Restore -SPFarm -Directory <Backup folder> -RestoreMethod Overwrite -Item <Content database name> [-BackupId] [-Verbose]

If you don’t know the BackupID you can display all the backups using the below command and get the GUID of the Backup.

Get-SPBackupHistory -Directory <Backup folder>

You can check all the Backup-Restore Operations Here


Deploy WebPart Soluiton Package

Install -SPWebPartPack -LiteralPath "PathToCABorwspFile" -Name "NameOFWebPart"

PathToCABorwspFile- is the full path to the CAB file that is being deployed.

NameOFWebPart- is the name of the Web Part that is being deployed.


Install Activate and Deactivate Feature using Windows Powershell


Install Feature :

$MyFeatureId = $(Get -SPFeature -limit all where {$_.displayname -eq "myfeatureName"}).Id

Install -SPFeature $MyFeatureId


Activate\Enable Feature :

$singleSiteCollection = Get -SPSite -Identity http://MySingleSiteCollectionURL

Enable -SPFeature $MyFeatureId -Url $singleSiteCollection.URL


Deactivate\Disable Feature :

$singleSiteCollection = Get-SPSite -Identity http://MySingleSiteCollectionURL

Disable -SPFeature $MyFeatureId -Url $singleSiteCollection.URL


Command TO List all the PowerShell Commands
Get-Command –PSSnapin “Get-Command –PSSnapin “Microsoft.SharePoint.
PowerShell” format-table name > C:\SP2010_PowerShell_Commands.txt

Check in documents with Powershell SharePoint 2010

A simple script shared at @ http://secretsofsharepoint.com/cs/ site for Checking in the documents in a document library using a powershell script.
function CheckInDocument([string]$url)
{
$spWeb = Get-SPWeb $url
$getFolder = $spWeb.GetFolder(“Shared Documents”)
$getFolder.Files | Where { $_.CheckOutStatus -ne “None” } | ForEach
{
Write-Host “$($_.Name) is Checked out To: $($_.CheckedOutBy)”
$_.CheckIn(“Checked In By Administrator”)
Write-Host “$($_.Name) Checked In” -ForeGroundColor Green
}
$spWeb.Dispose()
}
Here’s an example on running the function:
CheckInDocument http://SP

SharePoint 2010 PowerShell Permissions Explained

SharePoint 2010 has increased flexibility for administrative privileges of command line operations.  The end result is that there is a bit more complexity in setting up your administrative privileges, so I wanted to create a post to try and clear up administration permissions for SharePoint 2010. 
Foremost, please keep in mind that I’m going to discuss the minimum required privileges for each role—so there are lots of additional configurations; this is the just bare requirements.
First we need to talk about Central Administration, as the different permissions often lead to confusion.  To access Central Administration, you need to be a Farm Administration—aka, a member of the “Farm Administrators Group”.  This is really a UI only permission (I recommend you think of “Farm Adminstration Privs” as “The ability to use Central Admin”.  The reason for this is that Farm Administrators have the ability to run operations via-the Central Administation Web Application; keep in mind that no operation actually runs against the Configuration Database as the user but rather as the App Pool account for the Web App.
With STSADM and PowerShell, all commands are run as the user who executes the command (not through the Central Admin Web Application).  The good part about this is that any command can be run from any machine (no CA required), but this means that the user themselves needs the proper permissions.  With STSADM, the user required Box, Farm, and SQL permissions—way too much to run a truly “Least Privs” environment.  With 2010 there is the flexibility to only require PowerShell & SQL permissions*. 
                *Note: Box permissions are required for a small subset of commands that touch the Windows filesystem or registry.  Also, Box and SQL are required for all “setup” operations.
On that note, there are only two requirements for most commands.  The user must be:
·         A member of the WSS_ADMIN_WGP group (this is a Windows Group on the machine the user is executing commands on)
·         A member of the “SharePoint_Shell_Access” role on the configuration database (this is a SQL Role)
To simplify the management of these roles we have created a set of PowerShell commands (noun is “SPShellAdmin”) to add and remove Shell Administrators.  You’ll notice that the commands allow you to designate a specific database, this is because the “Shell Admin” role by default only gives the user access to the Configuration Database; the shell admin must be given access to each individual service and content database they are “allowed to manipulate” (i.e.: to delete a content database, the user must be a shell admin on that database).
                *IMPORTANT: The Shell Admin commands in SharePoint 2010 Beta do not fully setup these roles; you need to add the WSS_ADMIN_WGP role manually.
Please keep in mind that each command is just running object model, so additional permissions may be required for specific commands.  For example, you may need Service Application permissions to run commands against a certain service application.
Hopefully I’ve made permissions a little easier to understand—but if you’ve still got questions, put them in the comments section below.