SharePoint自动化系列——Add content type to list.

时间:2021-01-03 06:56:00

转载请注明出自天外归云的博客园:http://www.cnblogs.com/LanTianYou/

将创建好的content type(若是跨web application需要事先publish content type,并在Monitor中跑和Content type同步相关的job,这里我写好了一个脚本,一键执行所有和content type相关的jobs)添加到指定的SharePoint list中,代码如下(以下代码保存到桌面“AddCTToList.ps1”文件中):

Add-PSSnapin Microsoft.SharePoint.PowerShell

function AddCTToList()
{
    $webUrl = Read-Host "Enter the web url"
    $web = Get-SPWeb $webUrl
    $ListTitle = Read-Host "Enter the list title"
    $List = $web.Lists[$ListTitle]
    if ($List -ne $null)
    {
        $List.ContentTypesEnabled = $true
        $List.Update()
        $CTName = Read-Host "Enter the content type name"
        $CT = $web.ContentTypes[$CTName]
        $List.ContentTypes.Add($CT)
        $List.Update()
        Write-Host "Content type " $CT.Name " added to list " $ListTitle -ForegroundColor Green
    }
    else
    {
        Write-Host "The list " $ListTitle " does not exist in site " $web.Title
    }
}

AddCTToList

按提示先后输入:站点的url,list的title,content type的名字。调用方法如下:

SharePoint自动化系列——Add content type to list.

运行结果如下:

SharePoint自动化系列——Add content type to list.

之后在SharePoint中相应list的list setting页面我们可以看到,content type已经成功加入:

SharePoint自动化系列——Add content type to list.