Friday, November 14, 2014

Create SharePoint List Dynamically using Powershell Script


Create SharePoint List Dynamically using Powershell Script



In this post we will see how to create Sharepoint List dynamically using powershell script .


Please note that you can use notepad++ to write powershell scripts and save them with extension “.ps1″.


There are few variables which you need to assign some value e.g. site url and list name etc.

I would recommend to create this type of variables out side the function as I’ve done here.

Reason being is simple, you can use this variable in other functions in your script file.

Also, to make it workable we will add powershell Snap-in as mentioned in my last post.


Script:


#URL of the site where you wanna create your list dynamically.
$web = Get-SPWeb http://your site url

#List name
$ListName = "myList"
try

Write-Host "Adding PowerShell Snap-in" -ForegroundColor Green

# Try to get the PowerShell Snappin. If not, then adding the PowerShell snappin on the Catch Block
Get-PSSnapin "Microsoft.SharePoint.PowerShell"

catch

Add-PSSnapin "Microsoft.SharePoint.PowerShell"

Write-Host "Finished Adding PowerShell Snap-in" -ForegroundColor Green


#List type or template
$spTemplate = $web.ListTemplates["Custom List"]

#Get all the lists to the list collection
$spListCollection=$web.Lists

try

#adding the new list to the list collection
$spListCollection.Add($ListName,$ListName,$spTemplate)

Catch

Write-Host "Please Try Again..." -ForegroundColor Green
$web.Dispose()


Line $spTemplate = $web.ListTemplates["Custom List"] defines under which template we want our new list to be added.

In this example we are adding it to Custom List.


$spListCollection=$web.Lists will retrieve collection of existing sites and assign it to a variable.


$spListCollection.Add($ListName,$ListName,$spTemplate) will add a new list to Custom List template.


Now, I will explain how to Save and Execute this script.


Save this script with name e.g “CreateList.ps1”

To execute this open powershell management as administrator.

Goto the location where you saved your script

Type following command which will execute your script

PS C:\> .\CreateList.ps1


To check your list go to site contents and look for the list with name “myList”.



Create SharePoint List Dynamically using Powershell Script

No comments:

Post a Comment