SharePoint Create List and Insert Items Using PowerShell
cls
Remove-PSSnapin Microsoft.SharePoint.
Powershell -ErrorAction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint. Powershell
Remove-PSSnapin Microsoft.SharePoint.
Add-PSSnapin Microsoft.SharePoint.
# 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()
}
}
$webUrl = "http://sp2010:8080/personal/Test1/"
$web = Get-SPWeb $webUrl
$listName = "My List"
$listDescription = "Items"
$listTemplate = [Microsoft.SharePoint.
$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,$
$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($
$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
Post a Comment