SharePoint Create List and Insert Items Using PowerShell

cls
Remove-PSSnapin Microsoft.SharePoint.

Powershell -ErrorAction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.
Powershell
# varable description
$webUrl = "
http://sp2010:8080/personal/Test1/"
$web = Get-SPWeb $webUrl
$listName = "My List"
$listDescription = "Items"
$listTemplate = [Microsoft.SharePoint.SPListTemplateType]::GenericList #GenericList template

$listUrl = $web.ServerRelativeUrl + "/Lists/" + $listName;

#we can't use getlist here as the method raises filenotfoundexception if the list url is not there
$myCustomList = $web.Lists[$listName]
if($myCustomList -eq $null)
{
#Adding List
$lstId = $web.Lists.Add($listName,$
listDesc,$listTemplate)
$myCustomList = $web.GetList($listUrl) # use getlist here as the list already exists
$myCustomList.Update()
write-host "List created successfully" $listName
}
else
{
write-host "List already exists" $listName
}

# Adding Content to list
$list = $web.Lists.TryGetList($
listName)
$listItems = "--Select--","ABC","DEF","GHI","JKL","MNO","PQR"

$listItems | foreach {
$newItem = $list.Items.Add()
$newItem["Title"] = $_
$newItem.Update()
}
}


catch
{
write-host "Error" $_.exception
$errorlabel = $true
}


finally
{
if($web -ne $null)
{
$web.Dispose()
}

}

Comments

Popular posts from this blog

C# Copy files from one server to another

Suppress StyleCop SA1600

Telerik Rad Grid Sorting