Posts Tagged 'powershell'

How to export and import lists and libraries from a SharePoint 2010 site using Powershell

Let’s imagine this scenario:

You have an old SharePoint 2010 site and you need to copy its content to another SharePoint farm.  The site is heavily customized and moving it using traditional methods (backup/restore, export/import, save site as a template) are not going to work well.  Plus you only want content – no need to bring in all of that custom branding baggage.

You can copy the content using PowerShell and two scripts shown below.

Script # 1:   Export all lists and libraries from the source site.


add-pssnapin microsoft.sharepoint.powershell

# specify the site URL to export

$web = Get-SPWeb "http://sharepointURL/sites/site1/web1"

# specify output folder to store exported lists

$path = "c:\admin\export\"

foreach($list in $web.lists)

{

"Exporting " + $list.RootFolder.URL

export-spweb $web.URL -ItemUrl $list.RootFolder.URL -IncludeUserSecurity -IncludeVersions All -path ($path + $list + ".cmp") -nologfile

}

The output of this script should be a number of CMP files in the output directory.  Review these files and remove the lists that should not be imported (such as various Gallery lists).

Script # 2:  Import CMP files into the destination site.


add-pssnapin microsoft.sharepoint.powershell

# specify target SharePoint site to import into

$site = "http://sharepoint/sites/test1"

# specify folder containing exported lists

$folder = "C:\Admin\Import\"

$Files = Get-ChildItem $folder

foreach ($file in $files)
{

$name = $file.Name

"Importing: " + "$folder$name"

import-spweb $site -path ("$folder$name") -includeusersecurity -nologfile

}

How to remove webparts from a SharePoint page programmatically using Powershell

Let’s imagine this scenario:

You need to remove a webpart from a SharePoint page in your farm.   Easy, right?  Go to the page, enter the Edit mode, click on the webpart, select Delete.  No problem!   Now what if you had 1000 sites to remove the webpart from?   Doing it by hand is impractical, so we’ll need to use Powershell.

This will be a two step process:

Step 1, you need to run an inventory script which will generate a list of webparts and their GUIDs.

Step 2, you will use the webpart GUIDs from step 1 to run a removal script to remove the webparts.

STEP 1. INVENTORY SCRIPT

Execute the script below using the SharePoint 2010 Management Shell (PowerShell console).  This script does the following:

1. Iterate through all web applications in the farm and open every every site collection in each web app

2. For each site collection, access the homepage  “default.aspx” and capture a list of webparts on the page and their GUIDs.

3. Write the results to a file called “results.txt”, located in the same directory as the Powershell script.

The page name “default.aspx” is hard-coded in the script but can be easily changed to another page name or page path.

 

Script source code


[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | out-null

$oContentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService;

[Microsoft.SharePoint.Administration.SPWebApplicationCollection]$waColl = $oContentService.WebApplications;

$log = ".\results.txt"    # output file name and path
$pagepath = "/default.aspx"    # change page name or page path here

"Site URL; WebPart Title ; Webpart ID" | out-file $log

$waColl1 = $waColl | where-object {$_.IsAdministrationWebApplication -eq $FALSE}

foreach ($wa in $waColl1)
{

foreach ($obj in $wa.Sites) 
{

write-host "Processing: " , $siteURL

$siteURL = $obj.URL

$site=new-object Microsoft.SharePoint.SPSite($siteURL)

$pageURL = $siteURL + $pagepath  
$web=$site.Openweb()   
$webpartmanager=$web.GetLimitedWebPartManager($pageURL,  [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)   
foreach ($webpart in $webpartmanager.WebParts)
{   
$siteURL + "; " + $webpart.Title + " ;  " + $webpart.ID | out-file $log -append   
}                           
}

}

write-host "Finished."

 

STEP 2. WEBPART REMOVAL SCRIPT

This script  will programmatically remove a webpart from a SharePoint page.  It takes as arguments the target site URL and the webpart GUID.   The script targets the main page “default.aspx” but can be changed to accept any other page name or page path.

Notes: Use the results from the INVENTORY SCRIPT to create a list of webparts and their GUIDs to remove. Then build a script which calls out the WEBPART REMOVAL SCRIPT using the site URLs and webpart GUIDs as arguments.

The syntax is the following:

Execute the following command in SharePoint 2010 Management shell (Powershell console):

[WEBPART REMOVAL script file name] [site URL] [webpart GUID]

Example:

remove.ps1     http://mysharepointsite     a1b83-8tyu-6897-oiy8

 

Script source code


[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | out-null [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.WebPartPages") [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Publishing")

$siteURL = $args[0]  # first argument: site URL

$webpartId = $args[1]   # second argument:  webpart GUID

$pagepath =  "/default.aspx"        # change page name or page path here

$pageURL = $siteURL + $pagepath

write-host "Processing site: ", $siteURL

Write-host "Processing page: " , $pageURL

write-host "Processing webpart ID: " , $webpartID

$site=new-object Microsoft.SharePoint.SPSite($siteURL)

$web=$site.Openweb()

$webpartmanager=$web.GetLimitedWebPartManager($pageURL, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

$webpartmanager.DeleteWebPart($webpartmanager.Webparts[$webpartId])

$web.Update()

$web.Dispose()

write-host "Finished."

Create and delete SharePoint list views with PowerShell

Here’s how you can create and delete views in a SharePoint list or library using PowerShell (Is there anything that can’t be done through a PowerShell script?)

The script below creates a view called “TestView”.  It expects three command-line arguments:  site collection URL, the name of the view to create, and the list GUID.  The view that’s created is an exact replica of the “All Items” view (you can certainly modify the code as needed).  Here’s how you would call this script from the command line:


powershell  CreateView.ps1 "your_site_collection_URL" "TestView" "List GUID 6865306f-60e0-4889-addd-4fb9862e72e0"

Script code (use the button in the top right corner to copy it to the clipboard):


[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | out-null

# reading command line arguments

$siteURL = $args[0]

$strViewName = $args[1]

$ListGUID = $args[2]

# enter your CAML query for the view here...

$strQuery = "<Where><Gt><FieldRef Name='ID'/><Value Type='Counter'>0</Value></Gt></Where>"

 # create a new SPsite object and recursively go through all webs

# until a matching list GUID is found

$site=new-object Microsoft.SharePoint.SPSite($siteURL)

foreach ($web in $site.AllWebs)
{
 

foreach ($list in $web.Lists)
{

$ListTempGUID = $list.ID.ToString()
  

if ($ListTempGUID.Contains($ListGUID))
{

write-host "**********************************************"
write-host "Match found. Preparing to create a view: ", $strViewName
write-host "List Title: ", $list.Title
write-host "List GUID: ", $list.ID

$fields = $list.Views["All Items"].ViewFields.ToStringCollection()

$result = $list.Views.Add($strViewName, $fields, $strQuery, 100, $True, $False , "HTML", $False)

write-host "View ", $strViewName , " was created successfully."

break

}
}

} 

write-host "Done."

$site.Dispose(); ##ENFORCED DISPOSAL!!!

    

So far, so good?  Well, now that you’ve created a view, how do you delete it?  Follow the same logic, only instead of using the Add method of SPViewCollection object, we’ll be using the Delete method.

Same command line arguments as before:  site collection URL, name of the view, and list GUID.

Calling script from the command line:


powershell  DeleteView.ps1 "your_site_collection_URL" "TestView" "List GUID 6865346f-60e0-4889-addd-4fb3862572e0"

 


[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | out-null

# reading command line arguments...

$siteURL = $args[0]

$strViewName = $args[1]

$ListGUID = $args[2] 
# creating a new site object and recursively searching through its lists

# until a matching list GUID is found

$site=new-object Microsoft.SharePoint.SPSite($siteURL)

foreach ($web in $site.AllWebs)
{
 

foreach ($list in $web.Lists)
{

$ListTempGUID = $list.ID.ToString()
  

if ($ListTempGUID.Contains($ListGUID))
{
foreach ($view in $list.Views)
{

If ( $view.Title.Contains($strViewName))
{

write-host "**********************************************"
write-host "Match found. Preparing to DELETE a view: ", $view.Title
write-host "List Title: ", $list.Title
write-host "List GUID: ", $list.ID

# you can insert a pause here if you like...

$list.Views.Delete($view.ID)

write-host "View ", $view.Title , " has been deleted successfully."

break

}
}

break

}

}

}
write-host "Done."

$site.Dispose(); ##ENFORCED DISPOSAL!!! 
 

Finally,  how do you find out the GUID of your list?  It’s fairly straightforward – you just need to access the SPList.ID property of your list.  Here’s a simple script that will output the GUIDs of all lists in your site collection:


[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | out-null
# write column headings

write-host "List URL ; Web URL ; Web Title ; List Title; List GUID ;"

# create a site object and recursively list all of its list objects and their details
 $site=new-object Microsoft.SharePoint.SPSite("http://your_site_collection_URL)  

  foreach ($web in $site.AllWebs)
 {
  foreach ($list in $web.Lists)
 {
 write-host $list.DefaultViewURL, ";", $web.URL , ";",  $web.Title , ";" , $list.Title , ";" , $list.ID

 }

 }

$site.Dispose(); ##ENFORCED DISPOSAL!!!

Calling STSADM from within a PowerShell script

For various SharePoint admin tasks, there are times when you need to execute an STSADM command from within a PowerShell script. 

Before you can do that, you’ll need to tell PowerShell where to find STSADM executable. You can do that by adding the following line to your profile.ps1 file (usually located in C:\WINDOWS\system32\windowspowershell\v1.0 ):

Set-Alias -Name stsadm -Value $env:CommonProgramFiles”\Microsoft Shared\Web Server Extensions\12\BIN\STSADM.EXE”

Now you can use stsadm in your scripts and it should work beautifully…

Testing access to SharePoint pages

Let’s say you have a long list of SharePoint pages that need to be tested to verify that they’re permissioned correctly.  One way to do it is to take a non-privileged account (end user) and attempt to connect to each of the URLs.  If the page is locked down, you’ll get a page titled “Access denied”; otherwise, the page will load normally.

I recently responded to a thread on SharePoint TechNet about a similar issue and ended up writing a PowerShell script to address it.

The script below will read a text file containing a list of URLs (make sure to modify the source file path with your own path), and then call a function for each URL.  This function will open a new instance of IE, navigate to the URL, wait for the page to load, and then grab the title of the page.  If the user doesn’t have access to the page, the page title will contain “Access denied”; otherwise, the page title will be returned.  Run this script under the credentials of one of your end users.  If you’re trying to open individual documents (Word, Excel, etc.), you may need to modify the script so that it launches correct application (and closes it when done).


# This script will read a text file containing a list of URLs and attempt to connect to each URL.  Successful connection will return the page's title; otherwise, the script will return Access denied error.

# OpenIE function starts here...
# This function launches a new instance of IE and then navigates to the specified URL

function OpenIE($url)
{

if ($url -notlike "http://*")
{

$url = "http://" + $url

}
$ie = new-object -com "InternetExplorer.Application"

$ie.Visible = $true

$ie.Navigate($url)

# wait for IE to load the page

While( $ie.Busy )
{
[System.Threading.Thread]::Sleep(100)
}

# grab page title - if access is denied, the page title will say so

$Title = $ie.Document.Title

$ie.Quit()

return $Title

}

 

# *** Main script routine starts here ***
# specify your source file path here...

$SourceFilePath = "C:\Shared\list.txt"

write-host "Starting script..."

# read the source file into an array of strings, iterate through each one

$list = Get-Content $SourceFilePath

foreach ($item in $list)
{

$result = OpenIE($item)

write-host $item, ";" , $result

}

write-host "Finished."

Finding out where SharePoint email alias is used

Recently, a question came up in the SharePoint TechNet forums regarding document libraries with incoming email enabled.  If you only know the name of the AD contact for the library, how can you find out which document library or list it’s pointing to? 

Here’s a straightforward PowerShell script which will iterate through every site collection in every web application and return the names and email aliases of every list that has an active email alias specified.


[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c") | out-null

[void][System.reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$oContentService = [Microsoft.Sharepoint.Administration.SPWebService]::ContentService;

[Microsoft.SharePoint.Administration.SPWebApplicationCollection]$waColl = $oContentService.webApplications;

$waColl1 = $waColl | where-object {$_.IsAdministrationWebApplication -eq $FALSE}
write-host "WebApplication; Site Collection; List Title; List URL; EmailAlias"

foreach ($wa in $waColl1)
{

$sites = $wa.Sites

foreach ($obj in $sites)

{

$spSite = new-object Microsoft.SharePoint.SPSite($obj.URL)

$colWebsites = $spSite.AllWebs

foreach ($web in $colWebsites)
{

 $colLists = $web.Lists
 
 foreach ($list in $colLists)
 {

 if ( $list.EmailAlias -ne $null )
 {

 write-host  $wa.Name, ";", $obj.URL, ";", $list.Title , ";", $list.DefaultViewUrl, ";",  $list.EmailAlias

 }

 }

}

}

}

write-host "Finished."

List site users and their roles for all sites, using PowerShell

Last week, I had a specific task to find out who has Full control access to sites in our SharePoint environment. Fabrice Romelard has an excellent Powershell script to use to find out what permissions a specific user has within your environment:

(link: http://sharepointpsscripts.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=21699, fourth script).

The problem for me was, I didn’t know the logins of the users who had full control access. So I took Fabrice’s script and modified it to fit my needs (see code below).

This PS script will iterate through all of the site collections in your environment and output a list of users and their respective permissions (Reader, Contributor, Full Control, etc.).

—————————————————>8

[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”) > $null

function CheckPermissions([string]$webURL)
{

$site = new-object Microsoft.SharePoint.SPSite($webURL)
$myweb = $site.OpenWeb()
$mywebUsers = $myweb.Users

foreach($mywebUser in $mywebUsers)
{

$myPermissions = $myweb.Permissions

foreach($myPermission in $myPermissions)
{

if($mywebUser.ID -eq $myPermission.Member.ID)
{

foreach ($role in $mywebUser.Roles)
{

if ($role.Type -ne [Microsoft.SharePoint.SPRoleType]::None)
{

write-host $webURL , “; “, $mywebUser.LoginName , “; ” , $role.Type.ToString()

}

}
}
}
}

}

function StartProcess()
{
$oContentService = [Microsoft.SharePoint.Administration.SPWebService]::ContentService;

[Microsoft.SharePoint.Administration.SPWebApplicationCollection]$waColl = $oContentService.WebApplications;

$waColl1 = $waColl | where-object {$_.IsAdministrationWebApplication -eq $FALSE}

foreach ($wa in $waColl1)
{

$sites = $wa.Sites

foreach ($obj in $sites)
{

CheckPermissions $obj.Url

}

}

}

StartProcess

—————————————————–>8


RSS Information Week Headlines

  • An error has occurred; the feed is probably down. Try again later.

RSS SharePoint Team Blog

  • An error has occurred; the feed is probably down. Try again later.

RSS InfoPath Team Blog

  • An error has occurred; the feed is probably down. Try again later.

RSS Joel Oleson Blog

  • An error has occurred; the feed is probably down. Try again later.

RSS Susan Hanley’s KM Blog

  • An error has occurred; the feed is probably down. Try again later.

Blog Stats

  • 348,184 hits