通过PowerShell实现SharePoint列表增删改

通过 powershell 脚本实现 SharePoint 2010 列表项添加删除修改的例子。

添加列表项

$spAssignment = Start-SPAssignment
$mylist = (Get-SPWeb -identity http://SP -AssignmentCollection $spAssignment).Lists["listName"]
$newItem = $mylist.Items.Add()
$newItem["Title"] = “通过Powershell添加”
$newItem["description"] = “PowerShell 魔法”
$newItem.Update()
Stop-SPAssignment $spAssignment

更新列表项

$SPAssignment = Start-SPAssignment
$SPWeb = Get-SPWeb http://SP -AssignmentCollection $spAssignment

接下来是获取列表:

$SPList = $SPWeb.Lists["Announcements"]

当我们获取到列表后,就可以进一步获取列表项了。最直接的办法是调用 GetItemByID() 方法:

$SPItem = $SPList.GetItemById("1")

上面的例子需要我们知道列表项的ID。如果我们并不知道列表项ID,也可以使用 Where-Object 命令来替代:

$SPItem = $SPList.Items | Where { $_["Title"] -eq "New Announcement" }

当我们获取到列表项以后,就可以修改其内容了。

$SPItem[“Title”] = "我的标题"
$SPItem[“Body”] = "我的内容"

修改好该列表项后,还必须调用 Update() 方法来提交修改。

$SPItem.Update()

所以事情都完成后,通过 Stop-SPAssignment 命令来释放 SPWeb 对象。

Stop-SPAssignment $SPAssignment

删除列表项

下面的例子将对列表项进行遍历,读取列表项的名称,判断如果包含字符串“3”,则将其删除。

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$site = new-object Microsoft.SharePoint.SPSite("http://SP")
$relweburl = '/Docs"
$web = $site.openweb($relweburl)
$list=$web.Lists["testList"]
$listItems = $list.Items
$listItemsTotal = $listItems.Count

for ($x=$listItemsTotal-1;$x -ge 0; $x--)
{
if($listItems[$x].name.Contains("3"))
{
Write-Host("DELETED: " + $listItems[$x].name)
$listItems[$x].Delete()
}
} 

 

参考资料

Add,Update,Delete List items using powershell sharepoint 2010

posted @ 2012-08-13 15:11  Sunmoonfire  阅读(1223)  评论(0编辑  收藏  举报