powershell 从XML文件创建和配置站点(创建主页,库,添加webpart,创建组...)。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了powershell 从XML文件创建和配置站点(创建主页,库,添加webpart,创建组...)。相关的知识,希望对你有一定的参考价值。

<?xml version="1.0"?>
<Config>
	<ParentURL>http://rbla-sp2010-002/sites/Site1</ParentURL>
	<ParentVisitorsGroup>Site 1 Visitors</ParentVisitorsGroup>
	<MyProfileURL>http://rbla-sp2010-002/my/</MyProfileURL>
	<DefaultPicURL>http://rbla-sp2010-002/_layouts/images/O14_person_placeHolder_96.png</DefaultPicURL>
	<Sites>
		<Site name="Electrical vehicle" description="Lorem ipsum dolor sit amet, consectetur adipiscing elit." url="/electricalvehicle" leader="rbla\rbla">
			<user name="rbla\RBLA" />
			<user name="rbla\FTRI" />
		</Site>
		<Site name="Energy efficiency" description="Lorem ipsum dolor sit amet, consectetur adipiscing elit." url="/energyefficiency" leader="rbla\rbla">
			<user name="rbla\RBLA" />
			<user name="rbla\FTRI" />
		</Site>
		<Site name="Photovoltaic" description="Lorem ipsum dolor sit amet, consectetur adipiscing elit." url="/photovoltaic" leader="rbla\rbla">
			<user name="rbla\RBLA" />
			<user name="rbla\FTRI" />
		</Site>
		<Site name="Wind" description="Lorem ipsum dolor sit amet, consectetur adipiscing elit." url="/wind" leader="rbla\rbla">
			<user name="rbla\RBLA" />
			<user name="rbla\FTRI" />
		</Site>
		<Site name="Home automation" description="Lorem ipsum dolor sit amet, consectetur adipiscing elit." url="/homeautomation" leader="rbla\rbla">
			<user name="rbla\RBLA" />
			<user name="rbla\FTRI" />
		</Site>
		<Site name="Building automation" description="Lorem ipsum dolor sit amet, consectetur adipiscing elit." url="/buildingautomation" leader="rbla\rbla">
			<user name="rbla\RBLA" />
			<user name="rbla\FTRI" />
		</Site>
		<Site name="IKA" description="Lorem ipsum dolor sit amet, consectetur adipiscing elit." url="/ika" leader="rbla\rbla">
			<user name="rbla\RBLA" />
			<user name="rbla\FTRI" />
		</Site>
		<Site name="IPG" description="Lorem ipsum dolor sit amet, consectetur adipiscing elit." url="/ipg" leader="rbla\rbla">
			<user name="rbla\RBLA" />
			<user name="rbla\FTRI" />
		</Site>
	</Sites>
</Config>
# ----------------------------------------------
# Author: Romain Blanchard
# Date: 07.06.2012
# Description: Create and configure sites (create homepage, libraries, add webparts, create groups..) from XML file.
# ----------------------------------------------

# -- Initialize -- #
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Publishing") | Out-Null

#----- Creation fichier de logs -----#
$logfile = "./log.txt"
$logfileexist = Test-path $logfile
function write-log{ 
param( 
[string]$mytext, 
[string]$fgc 
) 
if(!$fgc){$fgc="Gray"}
write-host $mytext -foregroundcolor $fgc
write-output $mytext | out-file -filepath $logfile -append
} 
if ($logfileexist -eq "True"){ remove-item -path $logfile -Confirm:$false }

#----- Scan XML -----#
$xmlinput = [xml] (Get-Content "SitesList.xml")
$url = $xmlinput.Config.ParentURL
$parentgroupvisitor = $xmlinput.Config.ParentVisitorsGroup
$myprofileurl = $xmlinput.Config.MyProfileURL
$defaultpicurl = $xmlinput.Config.DefaultPicURL
$count = 0
$i = 1
Select-Xml -Path "SitesList.xml" -Xpath "/Config/Sites/Site" | ForEach-Object { 
$siteurl = $url+$_.Node.url
$sitename = $_.Node.name
$sitedescription = $_.Node.description
$siteleader = $_.Node.leader
	
	#----- Create subsite -----#
	$template = Get-SPWebTemplate "STS#0"
	if ($template -eq $null) {	Write-Warning "Template not found!" Red }
	else
	{
		
		#----- Testing Publishing feature -----#
		$publishingfeatureweb = Get-SPWeb $url
		$publishingfeature = $publishingfeatureweb.Features["94c94ca6-b32f-4da9-a9e3-1f3d343d7ecb"]
		if ($publishingfeature -eq $null)
		{ 
			write-log ""
			write-log "The publishing feature on parent website is not enable, please enable it." Red
			write-log ''
		}
		else 
		{ 	
			write-log ""
			write-log $siteurl Yellow
			write-log ""
			write-log "Site creation..."
			New-SPWeb  -url $siteurl -template $template -Name $sitename -Description $sitedescription -UniquePermissions | Out-Null
			Enable-SPFeature -Identity "PublishingWeb" -URL $siteurl
			$spweb = Get-SPWeb $siteurl
			write-log "Site successfully created!" Green

			#----- Create Sitegroups -----#
			write-log "Groups creation..."
			$ExistOwnersSiteGroup = $spweb.SiteGroups["$sitename Owners"]
			if ($ExistOwnersSiteGroup) { $spweb.SiteGroups.Remove("$sitename Owners") }
			$ExistMembersSiteGroup = $spweb.SiteGroups["$sitename Members"]
			if ($ExistMembersSiteGroup)	{ $spweb.SiteGroups.Remove("$spweb Members") }
			$ownerGroupleader = $spweb.Site.RootWeb.EnsureUser(“$siteleader”)
			$spweb.SiteGroups.Add(“$spweb Owners”, $spweb.Site.Owner, $ownerGroupleader, “Use this group to grant people full control permissions to the $spweb site”)
			$ownerGroup = $spweb.SiteGroups["$spweb Owners"]
			$ownerGroup.AllowMembersEditMembership = $false
			$ownerGroup.Update()
			$spweb.SiteGroups.Add(“$spweb Members”, $ownerGroupleader, $spweb.Site.Owner, “Use this group to grant people contribute permissions to the $spweb site”)
			$membersGroup = $spweb.SiteGroups["$spweb Members"]
			$membersGroup.AllowMembersEditMembership = $false
			$membersGroup.Update()
			$visitorsGroup = $spweb.SiteGroups["$parentgroupvisitor"]
			$visitorsGroup.AllowMembersEditMembership = $false
			$visitorsGroup.Update()	
			
			$ownerGroupAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($ownerGroup)
			$membersGroupAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($membersGroup)
			$visitorsGroupAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($visitorsGroup)
			$ownerRoleDefinition = $spweb.Site.RootWeb.RoleDefinitions["Full Control"]
			$membersRoleDefinition = $spweb.Site.RootWeb.RoleDefinitions["Contribute"]
			$visitorsRoleDefinition = $spweb.Site.RootWeb.RoleDefinitions["Contribute"]
			$ownerGroupAssignment.RoleDefinitionBindings.Add($ownerRoleDefinition)
			$membersGroupAssignment.RoleDefinitionBindings.Add($membersRoleDefinition)
			$visitorsGroupAssignment.RoleDefinitionBindings.Add($visitorsRoleDefinition)
			$spweb.RoleAssignments.Add($ownerGroupAssignment)
			$spweb.RoleAssignments.Add($membersGroupAssignment)
			$spweb.RoleAssignments.Add($visitorsGroupAssignment)

			write-log "Groups successfully created!" Green
			write-log "Users assignment..."	
			
			$_.Node | Select-Xml -Xpath "user" | ForEach-Object {
				try
				{
					$username = $_.Node.name
					$usertoadd = $spweb.Site.RootWeb.EnsureUser(“$username”)
					$membersGroup.AddUser($usertoadd)
					write-log "     $username successfully added to $sitename Members!"
				}
				catch { write-log "     Error when adding $username account, does it really exist?"  Red }	
			}
			$membersGroup.RemoveUser($spweb.Site.Owner)
			write-log "Users successfully added!"   Green
		  
			if($spweb -ne $null)
			{
				#----- Create Home Page -----#
				write-log "Homepage creation..."
				$pubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($spweb)
				$pubWeb.Navigation.InheritGlobal = $true
				$pageLayout = $pubWeb.GetAvailablePageLayouts() | Where-Object {$_.Title -eq "Leadership Stream"} #"Blank Web Part page"
				$page = $pubWeb.GetPublishingPages().Add("Home.aspx", $pageLayout)
				$PageContent = "" #Insert Page Content here.
				$item = $page.ListItem
				$item["Title"] = $sitename
				$item["Page Content"] = $PageContent
				$item.Update()
				write-log "Homepage successfully created!"  Green
				
				#----- Create Webparts -----#
				write-log "Webparts creation..."
				$file = $spweb.GetFile("Pages/Home.aspx")
				$manager = $file.GetLimitedWebPartManager([System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
									
					#----- Create Private Document Library -----#
					$listTemplate = $SPWeb.ListTemplates["Document Library"]
					$spweb.Lists.Add("Private Documents","Private Documents", $listTemplate) | Out-Null
					$list = $spweb.Lists["Private Documents"]
					$list.BreakRoleInheritance($true)
					$visitorsGroup = $spweb.SiteGroups["$parentgroupvisitor"]
					$list.RoleAssignments.Remove($visitorsGroup)
					$list.Title = "Private Documents"
					$list.Update()
					$spweb.Dispose()
					
					#----- Contact Details Webpart -----#
					$wp1 = New-Object "Microsoft.SharePoint.Portal.WebControls.ContactFieldControl"
					$wp1.Title = "Stream Leader"
					$wp1.Contact = $ownerGroupleader.id
					$manager.AddWebPart($wp1,"TopRightLeaderColumn", 1)
					
					#----- Members Webpart -----#
					$rootsiteSP = Get-SPSite $url
					
					Get-Content "Webparts\MembersWithPicture.webpart" | foreach { 
					$_ -replace 'SharePointGroupName',$membersGroup `
					   -replace 'SharePointMyProfileURL', $myprofileurl `
					   -replace 'SharePointUserNoPic', $defaultpicurl
					} | Set-Content "Webparts\webpart_temp_$i.webpart"			
					$fileDWP = "Webparts\webpart_temp_$i.webpart"
					$errorMsg = ""
					[Microsoft.SharePoint.SPList]$wpList = $rootsiteSP.GetCatalog([Microsoft.SharePoint.SPListTemplateType]::WebPartCatalog)
					$fileStream = ([System.IO.FileInfo](Get-Item $fileDWP)).OpenRead()
					[Microsoft.SharePoint.SPFolder]$wpFolder = $wpList.RootFolder
					[Microsoft.SharePoint.SPFile]$wpFile = $wpFolder.Files.Add("MembersWithPicture.webpart", $fileStream, $true)
					$wpFile.Update();
					[System.Xml.XmlReader]$xmlReader = [System.Xml.XmlReader]::Create($wpFile.OpenBinaryStream())
					$wp3 = $manager.ImportWebPart($xmlReader,[ref]$errorMsg)
					$wp3.Title = "People linked"
					$manager.AddWebPart($wp3, "TopRightLeaderColumn", 2);
					$i++
					$xmlReader.Close()
					
					#----- Tag Cloud Webpart -----#
					$wp3 = New-Object "Microsoft.SharePoint.Portal.WebControls.TagCloudWebPart"
					$wp3.Title = "Tag Cloud"
					$wp3.UserScope = "UnderUrlEveryone"
					$manager.AddWebPart($wp3,"TopRightLeaderColumn2", 3)

					#----- Document Webpart -----#
					$wp4 = New-Object "Microsoft.SharePoint.WebPartPages.XsltListViewWebPart"
					$list = $spweb.Lists["Documents"]
					$list.Fields.Add("Recommends","Text",0) | Out-Null
					$list.Fields.Add("Comments","Text",0) | Out-Null
					$spView = $spweb.GetViewFromUrl($siteurl + "/Documents/Forms/AllItems.aspx")
					$spView.ViewFields.Add($list.Fields["Comments"]) 
					$spView.ViewFields.Add($list.Fields["Recommends"])
					$spView.ViewFields.Delete($list.Fields["Modified"])
					$spView.ViewFields.Delete($list.Fields["Modified By"])			
					$spView.ViewFields.Delete($list.Fields["Checked Out To"])
					$spView.TabularView = $true
					$spView.Update()
					$wp4.ListId = $list.ID;
					$wp4.ViewGuid = $list.DefaultView.ID.ToString();
					$manager.AddWebPart($wp4,"BottomLefColumn", 1)					
					
					#----- Private Documents Webpart -----#
					$wp5 = New-Object "Microsoft.SharePoint.WebPartPages.XsltListViewWebPart"
					$list = $spweb.Lists["Private Documents"]
					$list.Fields.Add("Recommends","Text",0) | Out-Null
					$list.Fields.Add("Comments","Text",0) | Out-Null
					$spView = $spweb.GetViewFromUrl($siteurl + "/Private Documents/Forms/AllItems.aspx")
					$spView.ViewFields.Add($list.Fields["Comments"]) 
					$spView.ViewFields.Add($list.Fields["Recommends"])
					$spView.ViewFields.Delete($list.Fields["Modified"])
					$spView.ViewFields.Delete($list.Fields["Modified By"])
					$spView.TabularView = $true
					$spView.Update()
					$wp5.ListId = $list.ID;
					$wp5.ViewGuid = $list.DefaultView.ID.ToString();
					$manager.AddWebPart($wp5,"BottomLefColumn", 2)	
					
					#----- Forum Webpart -----#
					$wp6 = New-Object "Microsoft.SharePoint.WebPartPages.XsltListViewWebPart"
					$wp6.Title = "Forum"
					$list = $spweb.Lists["Team Discussion"]
					$spView = $spweb.GetViewFromUrl($siteurl + "/Lists/Team Discussion/AllItems.aspx")
					$spView.ViewFields.Delete($list.Fields["Created By"])
					$spView.TabularView = $true
					$spView.Update()
					$wp6.ListId = $list.ID;
					$wp6.ViewGuid = $list.DefaultView.ID.ToString();
					$manager.AddWebPart($wp6,"BottomLefColumn", 3)

				$page.CheckIn("")
				$page.listItem.File.Publish("")
				write-log "Webparts successfully created!"  Green
				
				#----- Assign Welcome Page -----#
				$rootFolder=$spweb.RootFolder
				$rootFolder.WelcomePage=”Pages/Home.aspx”
				$rootFolder.Update()
				$spweb.Update()
				$page.CheckOut()
				$page.CheckIn("")
				$page.listItem.File.Publish("")
				
				#----- Assign CSS and MasterPage -----#
				#$spweb.AlternateCssUrl = "/Style Library/theme.css" 
				#$spweb.MasterUrl = "/_catalogs/masterpage/masterpage.master" 
				
				#----- Count number of sites -----#
				$count++
			}
			
			else 
				{ 
					write-log "Site doesn't exist!"  Red 
				}
			
			$spweb.Dispose()
			write-log "Done."  Green
			write-log "-------------------------------------------------------"
		} #Else end
	} #Else end
} #Foreach end
#---- Display number of website created -----#
write-log ""
if ($count -eq 1) { write-log "$count site has been created!"  Red }
else { write-log "$count sites has been created!"  Red }
write-log ""

以上是关于powershell 从XML文件创建和配置站点(创建主页,库,添加webpart,创建组...)。的主要内容,如果未能解决你的问题,请参考以下文章

powershell 从XML输入管理用户配置文件的属性顺序(列出它们并重新排序)。

如何从 PowerShell 运行 *.exe 文件

powershell netsh 导入 xml 配置文件

如何改变PowerShell启动的默认目录

什么是Powershell?

powershell 此脚本为安全站点创建单元站点