Pages

Showing posts with label powershell. Show all posts
Showing posts with label powershell. Show all posts

Wednesday, 21 January 2015

Useful PowerShell Commands for SharePoint 2010

  • To get the current verion of SharePoint Installed:
     get-spfarm | select BuildVersion
 
  • Export a list from SharePoint 2010
    
    Export-SPWeb "http://sitecollection/subsite/subsubsite/subsubsubsite/" -itemurl "/subsite/subsubsite/subsubsubsite/Lists/myList" -path "e:\backups\myList.cmp"
    
    

Monday, 6 January 2014

PowerShell script to copy a SharePoint Document Library to a Local Path

PowerShell script to copy a SharePoint Document Library to a Local Path

I cannot take credit for this awesome script, it was done by JBMurphy.com

Function JBM-SharePoint-CopyDocumentLibraryLocal {
PARAM([Parameter(Mandatory=$true)]$SiteURL,
    [Parameter(Mandatory=$true)]$DocumentLibrary,
    [Parameter(Mandatory=$true)]$Destination)
$spWeb = Get-SPWeb -Identity http://$SiteURL
$list = $spWeb.Lists[$DocumentLibrary]
foreach ($listItem in $list.Items)
{
    $DestinationPath = $listItem.Url.replace("$DocumentLibrary","$Destination").Replace("/","\")
    write-host "Downloading $($listItem.Name) -> $DestinationPath"
    if (!(Test-Path -path $(Split-Path $DestinationPath -parent)))
    {
        write-host "Createing $(Split-Path $DestinationPath -parent)"
        $dest = New-Item $(Split-Path $DestinationPath -parent) -type directory
    }
    $binary=$spWeb.GetFile($listItem.Url).OpenBinary()
    $stream = New-Object System.IO.FileStream($DestinationPath), Create
    $writer = New-Object System.IO.BinaryWriter($stream)
    $writer.write($binary)
    $writer.Close()
}
$spWeb.Dispose()
Rererence: http://www.jbmurphy.com/2012/04/25/powershell-script-to-copy-a-sharepoint-document-library-to-a-local-path/ 

The site is not valid. The 'Pages' document library is missing.



The site is not valid. The 'Pages' document library is missing.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Microsoft.SharePoint.Publishing.InvalidPublishingWebException: The site is not valid. The 'Pages' document library is missing.


How to fix the problem?
To fix the issue it is required to update the value of the __PagesListId property value to match the ID of the Pages library.

This can be done (e.g.) through the following Powershell script:
$web = get-spweb http://site-collection/path-to-affected-site
$correctId = $web.Lists["Pages"].ID
$web.AllProperties["__PagesListId"] = $correctId.ToString()
$web.Update()

Reference: http://blogs.technet.com/b/stefan_gossner/archive/2011/09/15/common-error-the-site-is-not-valid-the-pages-document-library-is-missing-error.aspx

Tuesday, 11 June 2013

How to get a list of all activated features for a site collection and a sub site in SharePoint 2010 using powershell

To get a list of Site collection features:

Get-SPSite http://sharepoint2010 | % {

    $results = @()

    Get-SPFeature -Site $_ -Limit All | % {

    $feature = $_; 
        $featuresDefn = (Get-SPFarm).FeatureDefinitions[$_.ID]; 
        $cc = [System.Globalization.CultureInfo]::CurrentCulture;

        $obj = New-Object PSObject;
        $obj | Add-Member NoteProperty  Title  $($featuresDefn.GetTitle($cc));
        $obj | Add-Member NoteProperty  Hidden $($feature.Hidden);
        
        $results += $obj;
    }
    $results | FT -auto;
}
 
 
To get a list of features for a sub site:
 
Get-SPWeb http://sharepoint2010/subsite | % {

    $results = @()

    Get-SPFeature -Web $_ -Limit All | % {

        $feature = $_; 
        $featuresDefn = (Get-SPFarm).FeatureDefinitions[$_.ID]; 
        $cc = [System.Globalization.CultureInfo]::CurrentCulture;

        $obj = New-Object PSObject;
        $obj | Add-Member NoteProperty  Title  $($featuresDefn.GetTitle($cc));
        $obj | Add-Member NoteProperty  Hidden $($feature.Hidden);
        
        $results += $obj;
    }
    $results | FT -Auto;
} 


Shows both hidden and non-hidden features
 
Thanks to  Joe Rodgers (blogs.msdn.com/b/josrod/archive/2013/01/04/
powershell-to-list-activated-features-for-a-site-and-web.aspx)

Monday, 13 May 2013

How to create a new host named site collection in its own content database using Powershell


Step 1:  Add New Content Database to the Web Application
New-SPContentDatabase -Name <content_db_name> -WebApplication <web application URL>


Step 2: Get a reference to the hostnamed web application:
$webApp = Get-SPWebApplication "MyHostNamedWebApp" 
 
Step 3: Create a site collection 
new-spsite http://sharepointDev.com -ownerAlias "domain\user" -HostHeaderWebApplication $WebApp -ContentDatabase "WSS_Content_Dev_test" -template sts#0

Tuesday, 7 May 2013

BCS Throttle Management - SharePoint 2010

In order to check theBCS item limit run the following command:

$bdcProxy = Get-SPServiceApplicationProxy | where {$_.GetType().FullName -eq ('Microsoft.SharePoint.BusinessData.SharedService.' + 'BdcServiceApplicationProxy')}
  
$dbRule = Get-SPBusinessDataCatalogThrottleConfig -Scope Database -ThrottleType Items -ServiceApplicationProxy $bdcProxy


Result:
Scope: Database
ThrottleType: Items
Enforced: True
Default : 3000
Max: 1000000



Reference:
http://blogs.msdn.com/b/bcs/archive/2010/02/16/bcs-powershell-introduction-and-throttle-management.aspx 

Monday, 6 May 2013

Manage Visual Upgrades in sharePoint 2010

If you have a big site collection and some of the sub sites have not been upgraded to the UI version 4, then this powershell script will help:

# Gets the UI for each site in the


#create a txt file
"SitePath, SWebPath, UIVersion, UIVersion Configuration Enabled, MasterURL, Custom Master URL" > "UI-Version.txt" #Write the Headers in to a text file

$sc = Get-SPSite http://www.mySiteCollection.com; $sc.GetVisualReport() | Select-Object "SitePath", "SWebPath", "UIVersion", "UIVersion Configuration Enabled", "MasterURL", "Custom Master URL" >> UI-Version.txt

Restore a deleted site collection using PowerShell

In order to delete a sub site, one can recover using admin recyclebin. You can restore a sub site which has been deleted using the UI not SharePoint designer. But if you have to recover a site collection then you will need to use powershell.

Thanks to  Salaudeen Rajack


Get-SPDeletedSite - Displays list of sites deleted. 
Restore-SPDeletedSite - Restore a deleted site 
Remove-SPDeletedSite - To permanently remove the deleted site collection.

Permanently remove the deleted site collection:
Get-SPDeletedSite -webapplication http://sharepoint.company.com | Remove-SPDeletedSite

Wednesday, 10 April 2013

Issues faced when Copying/Moving a list in SP 2010





Just thought I will share my pain and some information that might safe guard you from making the same mistake as I did.

Problem:

User called up saying the list view has reached its threshold. The list was an Issues Register (name: Cut-Over Issues Register) and had versioning enabled. User requested we make a copy of list and name it “Issues Register” and delete all the closed items so only the Open items would remain in the new “Issues Register”

Solution:

Follow the technet article which uses PowerShell to export the list and then import the list back in. I found out this is not as easy as it looks in fact it was very hard and extremely painful, mainly due to the fact that the command does not cater for users that do not exist in AD anymore.

Why:
Well the list had versioning enabled and the worst part was that some of the users that had created an item have left NTG, which means the user account did not exist. So the restore process had overwritten the users that it could not find in AD with my user id and obviously that meant that we had lost the history.

Oh no… What can I do, unfortunately this is by design and the solution found on some forum sites was to reactivate those accounts in AD, copy the list and deactivate them again (not really an option if you have many users)

Things to do or look out for:

This exercise has highlighted some very important points:
·         If versioning is enabled on a list then do not copy/move. Suggest we create a new list based on the existing list definition and archive existing list by setting the list permission to read-only.
·         It can very difficult to recover your changes as even if you had a backup of the DB and thought you can just restore the list, you will not be able to do so. All the users that do not exist will be replaced with your user id, so in a sense you will never be able to recover an original list
·         If you get a request for a copy of a list, ensure there is no versioning enabled (List settings > versioning), if there is versioning then inform the requestor that they might lose historical info i.e. if any of the uses who modified/created an item and have left the organization then this will be replaced with your userid.

How to best solve the list view threshold issue (my recommendation):
·         Navigate to the list, then list settings, click on save as list template and specify a name (do not include content as most likely it will exceed the allowed file size of 500MB)
·         Create a new list based on the new template that you have created.
·         Archive the original list by setting the permission of the original list to read only.
·         This will need some planning before it carried out, as you may find that it may work in dev/uat but in PROD it won’t because of minimal testing carried out prior to moving your changes to PROD.


Monday, 4 March 2013

Add new MIME type - open PDF files directly in browser


Unable to open PDF/HTML/XML files directly in browser in SharePoint 2010? Default configuration of SharePoint 2010 does not consider PDF documents safe for displaying in the browser.This script adds new MIME type to "AllowedInlineDownloadedMimeTypes" property list of defined SharePoint 2010 Web Application.


 
If ( (Get-PSSnapin -Name "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null ) { 
    Add-PSSnapin "Microsoft.SharePoint.PowerShell" 
} 
 
Get-SPWebApplication 
 
$WebApp = Get-SPWebApplication $(Read-Host "`nEnter Web Application URL") 
 
Write-Host `n"Mime Type Examples:"`n"application/pdf, text/html, text/xml"`n 
 
If ($WebApp.AllowedInlineDownloadedMimeTypes -notcontains ($MimeType = Read-Host "Enter a required mime type")) 
{ 
  Write-Host -ForegroundColor White `n"Adding" $MimeType "MIME Type to defined Web Application"$WebApp.url 
  $WebApp.AllowedInlineDownloadedMimeTypes.Add($MimeType) 
  $WebApp.Update() 
  Write-Host -ForegroundColor Green `n"The" $MimeType "MIME type has been successfully added." 
} Else { 
  Write-Host -ForegroundColor Red `n"The" $MimeType "MIME type has already been added." 
}


Ref:
http://gallery.technet.microsoft.com/scriptcenter/Add-new-MIME-type-open-PDF-f6c57c32

Tuesday, 22 January 2013

How to activate a set of standard list of features in all site collections for a web application using Powershell in SharePoint 2010

Problem

The department has a site collection that is heavily used and is a key site collection.The business would like to standardise site collection features across the board. 
How to activate a standard list of features in all site collections for a web application using powershell script for SharePoint.

Solution:
Note: # is a comment in powershell

Contents of  ManualListofFeaturesInEDSite.txt - This contains all the features that need to be activated. If you do not wish to read from a text file and use a reference site then just use 

$allSiteColFeature = Get-SPFeature -site "http://muwebapp/sites/nintex" | Select displayname, id 
NintexWorkflow
NintexWorkflowWebParts
NintexWorkflowInfoPath
NintexWorkflowEnterpriseWebParts
NintexWorkflowContentTypeUpgrade
OfficeWebApps
OpenInClient
ReviewPublishingSPD1033
ReportServer
Reporting
PublishingSite
BaseSite
InPlaceRecords
LocationBasedPolicy
WAReports
DocumentSet
DocId
Workflows
LocationBasedPolicy
ViewFormPagesLockDown


 ***** Script begins here ******
  Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
Start-Transcript -path C:\Admin\SiteFeaturesoutput.txt -append

 $webs =  get-spsite -webapplication "http://mywebapp" -Limit All
 # Returns a detailed list of features, hence not being used
 #$allSiteColFeature = Get-SPFeature -site "http://muwebapp/sites/nintex" | Select displayname, id
 
 $fileContent = Get-Content "C:\drive\PROJECTS\DEVELOPMEN\ManualListofFeaturesInEDSite.txt"
 

#$oneweb = "http://mywebapp/sites/nintex"
   
    Foreach ($oneweb in $webs)
    {
        Foreach ($featureId in $fileContent)
        {
            #$siteFeature = get-spfeature -site $oneweb | Where {$_.id -eq $featureId.id}
            $siteFeature = get-spfeature -site $oneweb | Where {$_.displayname -eq $featureId.displayname}
           
            if ($siteFeature -eq $null)
            {
              Write-Host "Activating Site level Features at $oneweb FeatureID: $featureid" -foregroundcolor Yellow
               Enable-SPFeature $featureId -URL $oneweb.URL -Confirm:$False
              #Disable-SPFeature $featureId -URL $oneweb.URL -Confirm:$False
              #Enable-SPFeature $featureId -URL $oneweb -Confirm:$False
            }
            else
            {
              Write-Host "Feature $feature is already activated on $oneweb" -foregroundcolor green
            }
        }

    }

Stop-Transcript



****** End of Script ******

Tuesday, 20 November 2012

How to log the output to a text file for a powershell script

Problem

Some times when performing bulk operations you would want to log the output of a powershell script to a text file, so you can examine the results and perhaps even investigate what went wrong.

Solution:

Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
Start-Transcript -path C:\Admin\SiteFeaturesoutput.txt -append


.
.
Your script goes here
.
.
Stop-Transcript

Thursday, 25 October 2012

Extract a solution from the Content DB: SharePoint 2010

In order to gain access to a copy of a wsp file from the Config DB, follow these steps:

Powershell:

$farm = Get-SPFarm
$file = $farm.Solutions.Item("mySolution.wsp").SolutionFile
$file.SaveAs("c:\temp\mySolution.wsp")

To Get all solutions within a farm:
(Get-SPFarm).Solutions | ForEach-Object{$var = (Get-Location).Path + "\" + $_.Name; $_.SolutionFile.SaveAs($var)}

 

C#

using Microsoft.SharePoint
using Microsoft.SharePoint.Administration

namespace GetWSPFile
{
   class GetFile
   {
      static void Main(string[] args)
      {
           SPSolutionCollection AllSolutions = SPFarm.Local.Solutions;
           foreach (SPSolution solution in AllSolutions)
           {
              if(solution.Name =="mySolution.wsp")
              {
                     SPPersistedFile wspFile = solution.SolutionFile;
                     wspFile.SaveAs("C:\" + Solution.Name);
              }
           }
       }
    }
}