当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 使用 PowerShell 更改 SharePoint 中现有项目的内容类型

作者:精品下载站 日期:2024-12-14 13:46:20 浏览:18 分类:玩电脑

使用 PowerShell 更改 SharePoint 中现有项目的内容类型


要求:
我们有一个现有的文档库,其中包含 100 个销售提案文档。为了加强标准化,销售团队创建了一个内容类型“销售提案”。我们需要更改存储在特定文档库中的所有现有文档的内容类型,默认内容类型为“文档”。换句话说,现在需要为所有文档分配一个新的内容类型“销售提案”。

如何更改 SharePoint 中现有项目(文档)的内容类型?

您可以通过进入特定项目的编辑属性页面并切换“内容类型”字段来更改现有项目的内容类型。

[玩转系统] 使用 PowerShell 更改 SharePoint 中现有项目的内容类型

虽然更改 SharePoint 中现有项目的内容类型相对容易且直接,但您不希望浏览文档库中的每个文档并手动为其分配新的内容类型,因为这将非常耗时,不是吗?

好吧,让我们使用 PowerShell 让它变得快速而简单!此脚本循环访问给定文档库中存储的所有文档,检查每个文档的内容类型,如果是特定内容类型,则用新内容类型替换旧内容类型。

在运行此脚本之前,请先将新内容类型添加到您的库中!查找我的脚本:使用 PowerShell 将内容类型添加到 SharePoint 库

用于更改 SharePoint 中项目内容类型的 PowerShell 脚本


Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Custom PowerShell Function to switch Content type of all items stored in a SharePoint library
Function Change-ItemContentType {
    param(
        [Microsoft.SharePoint.SPWeb]$Web = $(throw "Please provide the 'Web' Parameter!"),
        [string]$ListName = $(throw "Please provide the 'ListName' Parameter!"),
        [string]$OldContentTypeName = $(throw "Please provide the 'OldContentTypeName' Parameter!"),
        [string]$NewContentTypeName = $(throw "Please provide the 'NewContentTypeName' Parameter!")
    )    
 
    #Get the list
    $List = $Web.Lists[$ListName]

    #Get the new content type
    $NewContentType = $List.ContentTypes[$NewContentTypeName]
 
    #Checkin any checked out file 
    foreach($item in $list.Items)
    {
        if($item.File.CheckOutStatus -ne "None")
        {
            #check file in            
            $item.File.CheckIn("Checked In By Administrator") 
            write-host "Checked-out file checked-in on item: "$item.id
        }
    }

    #Iterate through each item in the list 
    foreach($item in $list.Items)
    {
        if($item.ContentType.Name -eq $OldContentTypeName)
        {        
            #Change the content type
            $item.File.CheckOut()
            $item["ContentTypeId"] = $NewContentType.Id
            $item.SystemUpdate()
            $item.File.CheckIn("Content type changed to " + $NewContentType.Name, 1)
            Write-host "Content type changed for item: "$item.id
        }
    }
}

#Variables for processing
$WebURL ="https://sales.crescent.com"
$ListName ="Q1 Sales Proposals"
$ContentTypeName ="Sales Proposal"

#Get the Web and List
$Web = Get-SPWeb $WebURL
$List = $Web.lists.TryGetList($ListName)

if($list -ne $null)
{
    #Call the function to add content type
    Change-ItemContentType $web $list "document" "Sales Proposal"
}

这会将所有文档的旧内容类型“文档”更改为新内容类型“销售提案”。下次,当用户编辑文档时,系统会提示他们输入新内容类型的必填字段。

这是 SharePoint Online 的另一篇文章:PowerShell for SharePoint Online to Change Content Type

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯