PowerShell 在 SharePoint 中的内容类型中添加或删除字段
如果您需要向内容类型添加字段或从现有内容类型中删除字段,请使用以下 PowerShell 脚本:
用于将字段添加到内容类型的 PowerShell 脚本:
#Get Web Object
$web = Get-SPWeb "https://sharepoint.company.com"
#Get Content Type and Field
$ContentType=$web.ContentTypes["Content-Type-Name"]
$FieldToAdd=$web.Fields["Field-Name"]
#Add Field to Content type
$FieldLink=New-Object Microsoft.SharePoint.SPFieldLink($FieldToAdd)
$ContentType.FieldLinks.Add($FieldLink)
$ContentType.Update()
让我们添加一些错误处理并创建一个可重用的函数,以使用 PowerShell 将网站栏添加到内容类型!
PowerShell 将网站栏添加到 SharePoint 中的内容类型
#Add SharePoint Snap-in
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Function Add-FieldToContentType([Microsoft.SharePoint.SPWeb] $web, [string]$ContentTypeName, [string]$SiteColumnName)
{
#Get Content Type and Field (Site column) objects
$ContentType=$web.ContentTypes[$ContentTypeName]
#Check if the content type exists
if($ContentType -ne $null)
{
#Check if the content type has the Field already
if(!$ContentType.Fields.ContainsField($SiteColumnName))
{
#Check if the site column exists
if($web.Fields.ContainsField($SiteColumnName))
{
$FieldToAdd=$web.Fields.GetField($SiteColumnName)#[$SiteColumnName]
#Add Site column to the content type
$FieldLink= New-Object Microsoft.SharePoint.SPFieldLink($FieldToAdd)
$ContentType.FieldLinks.Add($FieldLink)
$ContentType.Update($true)
Write-Host "Site Column Field Added to the Content Type!" -ForegroundColor Green
}
else
{
Write-Host "Site Column Not Found!" -ForegroundColor Red
}
}
else
{
Write-Host "Field Exists Already!" -ForegroundColor Red
}
}
else
{
Write-Host "Content type not found!" -ForegroundColor Red
}
}
使用 PowerShell 从内容类型中删除字段:
以下是如何以编程方式从内容类型中删除网站栏
Function Remove-FieldFromContentType([Microsoft.SharePoint.SPWeb] $web, [string]$ContentTypeName, [string]$FieldNameToRemove)
{
#Get Content Type and Field (Site column) objects
$ContentType=$web.ContentTypes[$ContentTypeName]
#Check if the content type exists
if($ContentType -ne $null)
{
#Check if the content type has the Field
if($ContentType.Fields.ContainsField($FieldNameToRemove))
{
#Rempve the Field from the content type
$ContentType.FieldLinks.Delete($FieldNameToRemove)
$ContentType.Update($true)
Write-Host "Field removed from the Content Type!" -ForegroundColor Green
}
else
{
Write-Host "Field Doesn't Exists in the Content Type!" -ForegroundColor Red
}
}
else
{
Write-Host "Content type not found!" -ForegroundColor Red
}
}
现在,让我们使用 PowerShell 调用相应的函数来添加或删除内容类型中的网站栏:
#Configuration parameters
$WebURL="https://portal.crescent.com"
$ContentTypeName="CrescentInvestments"
$FieldName="FullName" # Internal Name of the field
#Get the Web
$Web = Get-SPWeb -Identity $WebURL
#Call the method to Add field to content type
Add-FieldToContentType $Web $ContentTypeName $FieldName
#Remove-FieldFromContentType $Web $ContentTypeName $FieldName
结果如下:
这以编程方式更新给定的内容类型。这是我关于将网站栏添加到 SharePoint 的 PowerShell 脚本的另一篇文章:使用 PowerShell 在 SharePoint 中创建网站栏
