如何使用 PowerShell 在 SharePoint 中上传列表模板?
要求:将自定义列表模板上传到 Web 应用程序中的特定网站集。虽然使用 SharePoint Web 界面上传列表模板很简单,但希望自动化此过程,因为它会重复多个网站集。
PowerShell 在 SharePoint 中上传列表模板:
以下是将自定义列表模板上传到 SharePoint 网站的 PowerShell 脚本:
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
#Define Variables
$WebURL = "https://intranet.crescent.com"
$TemplateFilePath = "C:\Downloads\Projects.stp"
#Get the Web
$web = Get-SPWeb $WebURL
#Get the List template Gallery Folder
$TemplateFolder = $web.GetFolder("List Template Gallery")
#Get List Templates collection
$TemplateFileCollection = $TemplateFolder.Files
#Get the Template file from Local File system
$TemplateFile = Get-ChildItem $TemplateFilePath
#Open the File in Read mode and Add to Templates collection
$TemplateFileCollection.Add("_catalogs/lt/$($TemplateFile.Name)", $TemplateFile.OpenRead(), $true)
Write-Host "Done! List Template has been uploaded!"
您可以通过导航到列表模板库来验证上传的模板:https://intranet.crescent.com/_catalogs/lt/Forms/AllItems.aspx
让我们将代码包装在函数内并添加一些错误处理。
使用 PowerShell 将列表模板上传到 SharePoint
此 PowerShell 脚本将列表模板上传到给定 Web 应用程序中的所有网站集。
Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
#Function to upload list template in all site collections in a web App
Function Upload-ListTemplate($WebAppURL, $TemplateFilePath)
{
Try {
#Get all site collections of the web app
$SiteCollection = Get-SPWebApplication $WebAppURL | Get-SPSite
#Get the Template file from Local File system
$TemplateFile = Get-ChildItem $TemplateFilePath
#Loop through each site collection
ForEach($Site in $SiteCollection)
{
Write-host "Uploading List Template to Site:"$Site.Url
#Try to Get the List template
$ListTemplate = $Site.GetCustomListTemplates($Site.RootWeb) | where {$_.InternalName -eq $TemplateFile.Name}
#Check if the list template exists
If($ListTemplate -eq $null)
{
#Uplod the List template file
$ListTemplateFile = $Site.RootWeb.GetFolder("_catalogs/lt").Files.Add("_catalogs/lt/$($TemplateFile.Name)", $TemplateFile.OpenRead(), $true)
write-host -f Green "`t List Template Uploaded to Site:"$Site.url
}
Else
{
write-host -f Yellow "`tList Template '$($TemplateFile.Name)' already exists!"
}
}
}
Catch {
write-host -f Red "Error Uploading List Template to Site!" $_.Exception.Message
}
}
#Define Variables
$WebAppURL = "https://intranet.crescent.com"
$TemplateFilePath = "C:\Downloads\projects.stp"
#Call the function to upload list template
Upload-ListTemplate -WebAppURL $WebAppURL -TemplateFilePath $TemplateFilePath
要将列表模板上传到 SharePoint Online,请使用:使用 PowerShell 将列表模板上传到 SharePoint Online
