您的位置:首页 > 运维架构 > Shell

Powershell 功能函数大全(Sharepoint 2013/2010)

2014-07-08 16:36 435 查看

Powershell功能函数大全

说明:本文章讲述powershell操作大全,是笔者多时积累完成。一步步从底层网站架构搭建,到网页内容的呈现,均由powershell完成。考虑到网站内容框架的移植,比如从开发环境到测试环境,再到产品环境,底层框架内容可由Powershell一键部署,这样更加方便以及可维护性。考虑到项目架构搭建的异同,初步分为以下步骤:

1.Poweshell对SiteColumn的完整操作

2.Powershell对ContentType的完整操作

3.Powershell对List的完整操作

4.Powershell对WebPart(页面)操作

5.Powershell对SecurityGroup操作

经过以上操作,整个空网站就搭建成功。

1.SiteColumn的创建

a.创建一般类型sitecolumn

functionCreateSiteColumn($siteUrl,$columnName,$type,$required,$unique){
try{
$site=new-objectMicrosoft.SharePoint.SPSite$siteUrl
$web=$site.RootWeb
$field=$web.Fields[$columnName]
if($field-ne$null){
$web.Fields.Delete($columnName)
$web.Update()
}

$fieldGroup="Retail"
$columnNameR=$columnName.Replace("","")
$newSiteColumn=$web.Fields.CreateNewField([Microsoft.SharePoint.SPFieldType]::$type,$columnNameR)
$newSiteColumn=$web.Fields.Add($newSiteColumn)
$field=$web.Fields[$columnNameR]

$field.Group=$fieldGroup
$field.Required=$required
$field.EnforceUniqueValues=$unique
$field.Title=$columnName
$field.Update()
$web.Update()
$site.Dispose()
LogWrite"successtocreatesitecolumn$columnName"
}
catch
{
LogWrite"failedtocreatesitecolumn$columnName"
LogWrite$_.Exception.Message
throw
}
}

b.创建RichText类型的sitecolumn

functionCreateSiteColumn-Richtext($siteUrl,$columnName,$required,$unique){
try{
$site=new-objectMicrosoft.SharePoint.SPSite$siteUrl
$web=$site.RootWeb
$field=$web.Fields[$columnName]
if($field-ne$null){
$web.Fields.Delete($columnName)
$web.Update()
}

$fieldGroup="Retail"
$columnNameR=$columnName.Replace("","")
$newSiteColumn=$web.Fields.CreateNewField([Microsoft.SharePoint.SPFieldType]::Note,$columnNameR)
$newSiteColumn=$web.Fields.Add($newSiteColumn)
$field=$web.Fields[$columnNameR]

$field.Group=$fieldGroup
$field.Required=$required
$field.EnforceUniqueValues=$unique
$field.Title=$columnName
$field.RichText=$true
$field.RichTextMode="Compatible"
#Compatible,FullHtml

$field.Update()
$web.Update()
$site.Dispose()
LogWrite"successtocreatesitecolumn$columnName"
}
catch
{
LogWrite"failedtocreatesitecolumn$columnName"
LogWrite$_.Exception.Message
throw
}
}

c.创建Calculated类型的sitecolumn

functionCreateSiteColumn-Calculated($siteUrl,$columnName,[Array]$calculateds){
try{
$site=Get-SPSite$siteUrl
$web=$site.RootWeb
$field=$web.Fields[$columnName]
if($field-ne$null){
$web.Fields.Delete($columnName)
$web.Update()
}
$formula="="
$calculateds|ForEach{
if($formula-eq"="){
$formula+="["+$_+"]"
}
else{
$formula+="+"+"["+$_+"]"
}
}
$columnNameR=$columnName.Replace("","")
$fieldGroup="Retail"
#$newSiteColumn=$web.Fields.CreateNewField($a,$columnName)
$newSiteColumn=$web.Fields.Add($columnNameR,[Microsoft.SharePoint.SPFieldType]::Calculated,$false)
$field=$web.Fields[$columnNameR]
$field.Formula=$formula
$field.OutputType="Number"
$field.Group=$fieldGroup
$field.Title=$columnName
$field.Update()
$web.Update()
$site.Dispose()
LogWrite"successtocreatesitecolumn$columnName"
}
catch
{
LogWrite"failedtocreatesitecolumn$columnName"
LogWrite$_.Exception.Message
throw

}

}



d.创建Choice类型的sitecolumn

functionCreateSiteColumn-Choice($siteUrl,$columnName,[Array]$choiceFieldChoices){
try{
$site=Get-SPSite$siteUrl
$web=$site.RootWeb
$field=$web.Fields[$columnName]
if($field-ne$null){
$web.Fields.Delete($columnName)
$web.Update()
}
$fieldGroup="Retail"
$columnNameR=$columnName.Replace("","")
#DeclareanewemptyStringcollection
$stringColl=new-ObjectSystem.Collections.Specialized.StringCollection
#Addthechoicefieldsfromarraytothestringcollection
$stringColl.AddRange($choiceFieldChoices)
$newSiteColumn=$web.Fields.Add($columnNameR,[Microsoft.SharePoint.SPFieldType]::Choice,$false,$false,$stringColl)
$field=$web.Fields[$columnNameR]
$field.Group="Retail"
$field.Title=$columnName
$field.Update()
$web.Update()
$site.Dispose()
LogWrite"successtocreatesitecolumn$columnName"
}
catch
{
LogWrite"failedtocreatesitecolumn$columnName"
LogWrite$_.Exception.Message
throw

}
}



e.创建Metadata类型sitecolumn

functionCreateSiteColumn-Metadata($siteUrl,$columnName,$fieldType,$isMulitple,$termStoreName,$termGroupName,$termSetName,$termName){
try{
#$fieldType:"TaxonomyFieldTypeMulti","TaxonomyFieldType"
$site=Get-SPSite-Identity$siteUrl
$rootWeb=$site.RootWeb
$field=$rootWeb.Fields[$columnName]
if($field-ne$null){
$rootWeb.Fields.Delete($columnName)
$rootWeb.Update()
}

$fieldGroup="Retail"
$columnNameR=$columnName.Replace("","")
#Createataxonomyfield
$field=[Microsoft.SharePoint.Taxonomy.TaxonomyField]$rootWeb.Fields.CreateNewField($fieldType,$columnNameR);

#Getataxonomysession
$session=new-objectMicrosoft.SharePoint.Taxonomy.TaxonomySession($site)

#GetTermStore
$termstore=$session.TermStores[$termStoreName]

#GetTermGroup
$group=$termstore.Groups[$termGroupName]

#GetTermSet
$termSet=$group.TermSets[$termSetName]

#populatenewlycreatedfield
$field.Sspid=$termSet.TermStore.Id
$field.TermSetId=$termSet.Id
if($termName-ne$null){
$terms=$termSet.GetAllTerms()
#GettheTermusingthename
$term=$terms|?{$_.Name-eq$termName}
$field.AnchorId=$term.Id
}
$field.AllowMultipleValues=$isMulitple
$field.Group=$fieldGroup
$field.Required=$false
$rootWeb.Fields.Add($field)
$rootWeb.Update()

$field=$rootWeb.Fields[$columnNameR]
$field.Title=$columnName
$field.Update()

#Updatespweb
$rootWeb.Update()
$site.Dispose()
LogWrite"successtocreatesitecolumn$columnName"
}
catch
{
LogWrite"failedtocreatesitecolumn$columnName"
LogWrite$_.Exception.Message
throw

}
}



2.ContentType的创建

a.创建congtenttype

functionCreateContenType($siteUrl,$contentTypeName,$parentContentType,[Array]$siteColumnNames){
try{
$spSite=Get-SPSite$siteUrl
$rootWeb=$spSite.RootWeb

$type=$rootWeb.ContentTypes[$contentTypeName]
if($type-ne$null){
$rootWeb.ContentTypes.Delete($type.Id)
$rootWeb.Update()
}

#$spWeb.AvailableContentTypes|SelectName
$parent=$rootWeb.AvailableContentTypes[$parentContentType]
$contentType=New-ObjectMicrosoft.SharePoint.SPContentType-ArgumentList@($parent,$rootWeb.ContentTypes,$contentTypeName)
$contentType.Group="Retail"
$rootWeb.ContentTypes.Add($contentType)
$rootWeb.Update()

$ct=$rootWeb.ContentTypes[$contentTypeName]
if($siteColumnNames-ne$null){
$siteColumnNames|ForEach{
$fieldAdd=$rootWeb.Fields[$_]
$fieldLink=New-ObjectMicrosoft.SharePoint.SPFieldLink($fieldAdd)
$ct.FieldLinks.Add($fieldLink)
}
}

$ct.Update()
$spSite.Dispose()
LogWrite"successtocreatecontenttype$contentTypeName"
}
catch{
LogWrite"faledtocreatecontenttype$contentTypeName"
LogWrite$_.Exception.Messag
throw
}

}


b.删除contenttype

functionDeleteContenType($siteUrl){
try{
$spSite=Get-SPSite$siteUrl
$rootWeb=$spSite.RootWeb
$type=$rootWeb.ContentTypes
$type|ForEach{

if($_.Group-eq"Retail"-and$_.Name-ne"RetailItemBase"-and$_.Name-ne"KnowledgeAsset"){
Write-Host$_.Name+$_.Id
$type.Delete($_.Id)
}

}
$rootWeb.Update()
$rootWeb.Update()
$spSite.Dispose()
LogWrite"successtodeletecontenttype$contentTypeName"
}
catch{
LogWrite"faledtodeletecontenttype$contentTypeName"
LogWrite$_.Exception.Messag
throw
}
}



c.更新Documentset

functionUpdateDocumentSet($siteUrl,$contentTypeSet,$contentType){
$spSite=Get-SPSite$siteUrl
$rootWeb=$spSite.RootWeb
$cty=$rootWeb.ContentTypes[$contentType].Id
$dsct=$rootWeb.ContentTypes[$contentTypeSet]
$dst=[Microsoft.Office.DocumentManagement.DocumentSets.DocumentSetTemplate]::GetDocumentSetTemplate($dsct)
$dst.AllowedContentTypes.Add($cty)
$dst.AllowedContentTypes.Remove("0x0101")
$dst.Update($true)
$spSite.Dispose()
}



3.创建list

a.创建list

functionAdd-SPList([string]$url,[string]$name,[string]$type){
try{
$spWeb=Get-SPWeb$url
#Checklistisexistornot
$spList=$spWeb.Lists[$name]
$templateType=$spWeb.ListTemplates[$type]
if($spList-ne$null){
$spList.Delete()
LogWrite"successtodeletethelistnamed$name"
}
[void]$spWeb.Lists.Add($name,"",$templateType)
LogWrite"successtoAddthelistnamed$name"
}
catch{
LogWrite"failedtoaddlistnamed$name"
LogWrite$_.Exception.Message
throw
}
finally{
$spWeb.Dispose()
}
}


b.创建View

functionAdd-SPListViewByFields([string]$webUrl,[string]$listName,[string]$listViewName,$viewName,$fieldsNames,$query。$scope){
try{
$spWeb=Get-SPWeb$webUrl
$spList=$spWeb.Lists[$listName]
if($spList-eq$null){
LogWrite"listnamed$listNameisnotexsiting"
return
}

$fields=$spList.Views[$listViewName].ViewFields.ToStringCollection()
$fields.Clear()
$fieldsNames|ForEach{
$fields.Add($_)
}

$strQuery=""
if($query-ne$null){
$strQuery=$query
}
$spList.Views.Add($viewName,$fields,$strQuery,10,$True,$False,"HTML",$False)
$view=$spList.Views[$viewName]

#$view.Scope="RecursiveAll"

if($scope-ne$null){

$view.Scope=$scope

}

$view.Update()
LogWrite"succesaddthelistviewnamed$viewNameinlist$listName"
}
catch
{
LogWrite"failedtoAddSPListView$listViewNameinlist$listName"
LogWrite$_.Exception.Messagethrow
}
finally{
$spWeb.Dispose()
}
}

c.添加sitecolumn到list

functionAdd-SiteColumn([string]$siteUrl,$webUrl,[string]$listName,[Array]$fieldNames){
try{
$spSite=Get-SPSite$siteUrl
$spWeb=Get-SPWeb$webUrl
$spList=$spWeb.Lists.TryGetList($listName)
if($spList-ne$null){
$fieldNames|ForEach{
$listField=$spSite.rootweb.Fields[$_]
$spList.Fields.Add($listField)
}
LogWrite"successtoaddsitecolumn$fieldNamesinlist$listName"
}
else{
LogWrite"failedtoaddsitecolumn$fieldNamesinlist$listNameforthelistisnoeexisting"
}

}
catch{
write-host"(ERROR:"$_.Exception.Message")"
LogWrite"failedtoaddsitecolumn$fieldNamesinlist$listName"
LogWrite$_.Exception.Message
throw
}
finally{
$spWeb.Dispose()
$spSite.Dispose()
}

}



d.添加field到view

functionAddViewField([string]$url,[string]$listName,$viewName,[Array]$fieldName){
try{
$spWeb=Get-SPWeb$url
$spList=$spWeb.Lists[$listName]
if($spList-ne$null){
$view=$spList.Views[$viewName]
$viewFields=$view.ViewFields
$fieldName|ForEach{
$viewFields.Add($_)
}
$view.Update()
LogWrite"successtoaddlistviewfield$fieldNameinlist$listName"
}
else{
LogWrite"Thelist$listNameisnotexitinginthesite"
throw
}
}
catch{
write-host"(ERROR:"$_.Exception.Message")"
LogWrite"failedtoaddlistviewfield$fieldNamenlist$listName"
LogWrite$_.Exception.Message
throw
}
finally{
$spWeb.Dispose()
}
}



e.添加contenttype到list

functionAddContentTypeToList($siteUrl,$webUrl,$listName,$contentTypeName)
{
$spSite=Get-SPSite$siteUrl
$spWeb=Get-SPWeb$webUrl
$rootWeb=$spSite.rootweb
$contentTypes=$rootWeb.ContentTypes

try{
#Checklistisexistornot
$list=$spWeb.Lists[$listName]
if($list-ne$null){
$contentType=$contentTypes|where{$_.Name-eq$contentTypeName}
if($contentType-ne$null){
$list.ContentTypesEnabled=$true
$list.Update()

$listCT=$list.ContentTypes|where{$_.Name-eq$contentTypeName}
if($listCT-eq$null){
$contentType=$rootWeb.ContentTypes[$contentTypeName]
$list.ContentTypes.Add($contentType)
$list.Update()
LogWrite"successtoaddcontenttype$contentTypeNameinlist$listName"
}
else{
$list.ContentTypes.Delete($listCT.Id)
$list.Update()
LogWrite"successtodeletecontenttype$contentTypeNameinlist$listName"
$list.ContentTypes.Add($contentType)
$list.Update()
LogWrite"successtoaddcontenttype$contentTypeNameinlist$listName"
}

}
else{
LogWrite"ThecontentType$contentTypeNameisnotexitinginthesite"
throw
}

}
else{
LogWrite"Thelist$listNameisnotexistinginthesite"
throw
}

}

catch{
LogWrite"failedtoaddcontenttype$contentTypeNameinlist$listName"
LogWrite$_.Exception.Message
throw
}

finally{
$spWeb.Dispose()
$spSite.Dispose()
}
}



f.删除contenttype

functionDeleteContentType($siteUrl,$webUrl,$listName,$contentTypeName)
{
$spSite=Get-SPSite$siteUrl
$spWeb=Get-SPWeb$webUrl
$rootWeb=$spSite.rootweb
$contentTypes=$rootWeb.ContentTypes

try{

$contentType=$contentTypes|where{$_.Name-eq$contentTypeName}
if($contentType-ne$null){
$list=$spWeb.Lists[$listName]
if($list-ne$null){
$listCT=$list.ContentTypes|where{$_.Name-eq$contentTypeName}
if($listCT-ne$null){
$list.ContentTypes.Delete($listCT.Id)
$list.Update()
LogWrite"successtodeletecontenttype$contentTypeNameinlist$listName"
}
else{
LogWrite"ThecontentType$contentTypeNameisnotexitinginthelist$listName"
}
}
else{
LogWrite"Thelist$listNameisnotexitinginthesite"
}

}
else{
LogWrite"ThecontentType$contentTypeNameisnotexitinginthesite"
}

}

catch{
write-host"(ERROR:"$_.Exception.Message")"
LogWrite"failedtodeletelistcontenttype$contentTypeNameinlist$listName"
LogWrite$_.Exception.Message
throw
}

finally{
$spWeb.Dispose()
$spSite.Dispose()
}
}

g.改变contenttypeinlistitems

functionChangeContentType($webUrl,$listName,$oldContentType,$newContentType){
$web=Get-SPWeb$webUrl
$rootWeb=$web.Site.RootWeb
$folderFilter=$rootWeb.ContentTypes[$newContentType]
$folder=$rootWeb.ContentTypes[$oldContentType]
#$query.ViewXml="<Eq><FieldRefName='FSObjType'/><ValueType='Integer'>1</Value></Eq>"
$query=New-ObjectMicrosoft.SharePoint.SPQuery
$query.ViewAttributes="Scope=RecursiveAll"
$list=$web.Lists[$listName]
$items=$list.GetItems($query)
foreach($itemin$items){
write-host$item.Name
if(($item.ContentType.Name-eq$folder.Name)){
write-host"folder-"$item.Name
$itemR=$list.GetItemById($Item.ID)
$itemR["ContentTypeId"]=$folderFilter.Id
$itemR.SystemUpdate()
}
}
$web.Dispose()

}



4.添加webpart

a.添加webpart

functionAddWebPartPublish($webUrl,$pagePath,$listName,$listViewName,$title,$jsLink,$webpartZone,$index)
{
$pageUrl=$webUrl+$pagePath
$spWeb=Get-SPWeb$webUrl-ErrorActionStop

[Microsoft.SharePoint.Publishing.PublishingWeb]$pubWeb=[Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($spWeb)
$allowunsafeupdates=$spWeb.AllowUnsafeUpdates
$spWeb.AllowUnsafeUpdates=$true
$page=$spWeb.GetFile($pageUrl)

try{
$list=$spWeb.Lists.TryGetList($listName)
if($list-ne$null){

if($list.Views[$listViewName]-eq$null){
LogWrite"lackofviewnamed$listViewNameinlist$listName"
return
}

if($page.Level-eq[Microsoft.SharePoint.SPFileLevel]::Checkout)
{
if($page.CheckedOutBy.UserLogin-ne$spWeb.CurrentUser.UserLogin)
{
$page.UndoCheckOut()
$page.CheckOut()
}
}
else
{
$page.CheckOut()
}

#InitialisetheWebpartmanagerforthespecifiedprofilepage.
$spWebPartManager=$spWeb.GetLimitedWebPartManager($pageUrl,[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$ListViewWebPart=New-ObjectMicrosoft.SharePoint.WebPartPages.XsltListViewWebPart
$listViewWebPart.Title=$listName
$ListViewWebPart.ListName=($list.ID).ToString("B").ToUpper()
$ListViewWebPart.ViewGuid=($list.Views[$listViewName].ID).ToString("B").ToUpper()
$ListViewWebPart.Title=$title
$ListViewWebPart.JSLink=$jsLink

$spWebPartManager.AddWebPart($ListViewWebPart,$webpartZone,$index)
#$spWebPartManager.SaveChanges($ListViewWebPart)

}
else{
LogWrite"Thelistnamed$listNameisnotexisting"
return
}

#Checktoensurethepageischeckedoutbyyou,andifso,checkitin
if($page.CheckedOutBy.UserLogin-eq$spWeb.CurrentUser.UserLogin)
{
$page.CheckIn("PagecheckedinautomaticallybyPowerShellscript")
}

$page.Publish("Published")
$pubWeb.Close()
LogWrite"successtoadd$titlewebpart"
}

catch
{
$page.UndoCheckOut()
LogWrite"failedtoadd$titlewebpart"
LogWrite$_.Exception.Message

}

finally
{
#$spWebPartManager.Dispose()
$spWeb.Dispose()
}

}



b.删除页面上所有webpart

functionRemoveWebPart($siteUrl,$pagePath)
{
$pageUrl=$siteUrl+$pagePath
$spWeb=Get-SPWeb$siteUrl-ErrorActionStop

[Microsoft.SharePoint.Publishing.PublishingWeb]$pubWeb=[Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($spWeb);
$allowunsafeupdates=$spWeb.AllowUnsafeUpdates
$spWeb.AllowUnsafeUpdates=$true

$page=$spWeb.GetFile($pageUrl);
if($page.Level-eq[Microsoft.SharePoint.SPFileLevel]::Checkout)
{
if($page.CheckedOutBy.UserLogin-eq$spWeb.CurrentUser.UserLogin)
{
write-host"Pagehasalreadybeencheckedout"
}
else
{
$SPWeb.CurrentUser.LoginName
$page.UndoCheckOut()
$page.CheckOut()
write-host"Checkoutthepageoverride"
}

}
else
{
$page.CheckOut()
write-host"Checkoutthepage"
}
try{
#InitialisetheWebpartmanagerforthespecifiedprofilepage.
$spWebPartManager=$spWeb.GetLimitedWebPartManager($pageUrl,[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$flag=0
#CirclealltheWebpartsinthespecifiedpage
foreach($webpartin$spWebPartManager.WebParts)
{
try{
$spWebPartManager.DeleteWebPart($spWebPartManager.WebParts[$webpart.ID])
$spWebPartManager.SaveChanges($webpart)
}
catch{
write-host"(ERROR:"$_.Exception.Message")"
}
}

#Checktoensurethepageischeckedoutbyyou,andifso,checkitin
if($page.CheckedOutBy.UserLogin-eq$spWeb.CurrentUser.UserLogin)
{
$page.CheckIn("PagecheckedinautomaticallybyPowerShellscript")
Write-Output"Pagehasbeencheckedin"
}

$page.Publish("Published")
Write-Output"Pagehasbeenpublishedsuccess"
$pubWeb.Close()
$spWeb.Update()
}

catch
{
write-host"(ERROR:"$_.Exception.Message")"
}

finally
{
$spWeb.Dispose()
}

}


c.添加contenteditorwebpart

functionAddContentEditorWebPart($webUrl,$pagePath,$title,$webpartZone,$index,$content){
$pageUrl=$webUrl+$pagePath
$spWeb=Get-SPWeb$webUrl-ErrorActionStop

[Microsoft.SharePoint.Publishing.PublishingWeb]$pubWeb=[Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($spWeb);
$allowunsafeupdates=$spWeb.AllowUnsafeUpdates
$spWeb.AllowUnsafeUpdates=$true
$page=$spWeb.GetFile($pageUrl)
try{

if($page.Level-eq[Microsoft.SharePoint.SPFileLevel]::Checkout)
{
if($page.CheckedOutBy.UserLogin-ne$spWeb.CurrentUser.UserLogin)
{
$page.UndoCheckOut()
$page.CheckOut()
}
}
else
{
$page.CheckOut()
}

#InitialisetheWebpartmanagerforthespecifiedprofilepage.
$spWebPartManager=$spWeb.GetLimitedWebPartManager($pageUrl,[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$ListViewWebPart=New-ObjectMicrosoft.SharePoint.WebPartPages.ContentEditorWebPart
$listViewWebPart.Title=$title

$docXml=New-ObjectSystem.Xml.XmlDocument
$contentXml=$docXml.CreateElement("div")

$contentXml.set_InnerText($content)
$docXml.AppendChild($contentXml)

$listViewWebPart.Content=$contentXml

#$listViewWebPart.Content=$conetnt

$spWebPartManager.AddWebPart($ListViewWebPart,$webpartZone,$index)
$spWebPartManager.SaveChanges($ListViewWebPart)

#Checktoensurethepageischeckedoutbyyou,andifso,checkitin
if($page.CheckedOutBy.UserLogin-eq$spWeb.CurrentUser.UserLogin)
{
$page.CheckIn("PagecheckedinautomaticallybyPowerShellscript")
}

$page.Publish("Published")
$pubWeb.Close()
LogWrite"successtoadd$listNamewebpart"
}

catch
{
$page.UndoCheckOut()
LogWrite"failedtoadd$listNamewebpart"
LogWrite$_.Exception.Message

}

finally
{
$spWeb.Dispose()
}
}



d.添加filterwebpartconnections

functionAddSPWebPartConnections($webUrl,$pagePath,$listViewTitle,$filterTitle,$filterFieldName){
return
$web=Get-SPWeb$webUrl
[Microsoft.SharePoint.Publishing.PublishingWeb]$pubWeb=[Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)
$web.AllowUnsafeUpdates=$true
$page=$web.GetFile($webUrl+$pagePath)
try{

if($page.Level-eq[Microsoft.SharePoint.SPFileLevel]::Checkout)
{
if($page.CheckedOutBy.UserLogin-ne$web.CurrentUser.UserLogin)
{
$page.UndoCheckOut()
$page.CheckOut()
}
}
else
{
$page.CheckOut()
}

$wpManager=$web.GetLimitedWebPartManager($webUrl+$pagePath,[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$webpartListView=$wpManager.WebParts|where{$_.Title-eq$listViewTitle}
$webpartFilter=$wpManager.WebParts|Where{$_.Title-eq$filterTitle}

if($webpartListView-eq$null-or$webpartFilter-eq$null){
LogWrite"thewebpartnamed$listViewTitleor$filterTitleisnotexisting"
$page.UndoCheckOut()
return
}

$conWP=$wpManager.GetConsumerConnectionPoints($webpartListView)["DFWPFilterConsumerID"]
$provWP=$wpManager.GetProviderConnectionPoints($webpartFilter)[0]
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$trans=New-ObjectMicrosoft.SharePoint.WebPartPages.TransformableFilterValuesToParametersTransformer
[Array]$consumerArray=$($filterFieldName)
[Array]$providerArray=$($filterFieldName)
if($filterFieldName-eq"RetailRole"){
$providerArray=$("Roles")
}
$trans.ProviderFieldNames=$providerArray
$trans.ConsumerFieldNames=$consumerArray
$newCon=$wpManager.SPConnectWebParts($webpartFilter,$provWP,$webpartListView,$conWP,$trans)
$wpManager.SPWebPartConnections.Add($newCon)

#Checktoensurethepageischeckedoutbyyou,andifso,checkitin
if($page.CheckedOutBy.UserLogin-eq$web.CurrentUser.UserLogin)
{
$page.CheckIn("PagecheckedinautomaticallybyPowerShellscript")
}
$page.Publish("Published")
$pubWeb.Close()
LogWrite"SuccesstoaddConnecntionofFilterwebpart"
}
catch
{
$page.UndoCheckOut()
LogWrite"failedtoadd$ForumListNamewebpart"
LogWrite$_.Exception.Message

}

finally
{
$web.Dispose()
}
}



e.天津自定义webpart

functionAddBoxWebpart($webUrl,$pagePath,$zone,$index,$title,$listName,$titleUrl)
{
$pageUrl=$webUrl+$pagePath
$spWeb=Get-SPWeb$webUrl-ErrorActionStop
$topWeb=$spWeb.Site.RootWeb

[Microsoft.SharePoint.Publishing.PublishingWeb]$pubWeb=[Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($spWeb)
$allowunsafeupdates=$spWeb.AllowUnsafeUpdates
$spWeb.AllowUnsafeUpdates=$true
$page=$spWeb.GetFile($pageUrl)
try{
if($page.Level-eq[Microsoft.SharePoint.SPFileLevel]::Checkout)
{
if($page.CheckedOutBy.UserLogin-ne$spWeb.CurrentUser.UserLogin)
{
$page.UndoCheckOut()
$page.CheckOut()
}
}
else
{
$page.CheckOut()
}

$webPartGallery=$topWeb.Lists["WebPartGallery"]
$webpart=$webPartGallery.Items|?{$_.Name-eq"StorePortal2014_Box.webpart"}
$webpartmanager=$topWeb.GetLimitedWebPartManager($pageUrl,[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$errorMsg=""
$xmlReader=New-ObjectSystem.Xml.XmlTextReader($webpart.File.OpenBinaryStream());
$webpart=$webpartmanager.ImportWebPart($xmlReader,[ref]"Error")
$webpart.LisName=$listName
$webpart.Title=$title
$webpart.TitleUrl=$titleUrl
$webpartmanager.AddWebPart($webpart,$zone,$index);

#Checktoensurethepageischeckedoutbyyou,andifso,checkitin
if($page.CheckedOutBy.UserLogin-eq$spWeb.CurrentUser.UserLogin)
{
$page.CheckIn("PagecheckedinautomaticallybyPowerShellscript")
}
$page.Publish("Published")
$pubWeb.Close()
LogWrite"Successtoadd$listNamewebpart"
}

catch
{
$page.UndoCheckOut()
LogWrite"failedtoadd$listNamewebpart"
LogWrite$_.Exception.Message

}

finally
{
$topWeb.Dispose()
$spWeb.Dispose()
}
}


5.根据不同layout添加页面

a.创建页面

functionCreatePage($webUrl,[Array]$pageNames,$layout,$folderName){
try{
$spWeb=Get-SPWeb$webUrl
$list=$spWeb.Lists["Pages"]
#GetPublishingWeb
$pubWeb=[Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($spWeb)
#Findstheappropriatepagelayout
#SpDesktopV2HomePage.aspx
#SpDesktopV2TermPage.aspx
#SpDesktopV2OnePartZone.aspx
$layout=$pubWeb.GetAvailablePageLayouts()|Where{$_.Name-eq$layout}
$query=new-objectMicrosoft.SharePoint.SPQuery
$query.ViewAttributes="Scope='Recursive'"
if($folderName-ne$null){
$query.Folder=$list.RootFolder.SubFolders[$folderName]
}
$pages=$pubWeb.GetPublishingPages($query)
$pageNames|Foreach{
#Createthepage;
$page=$pages.Add($_,$layout)
#CheckinPage
$page.CheckIn("Cretaepage")
$page.ListItem.File.Publish("PublishComment")
if($_-eq"Home.aspx"){
#Setnewpagetobethewelcome(homepage)
$rootFolder=$spWeb.RootFolder
$rootFolder.WelcomePage="Pages/home.aspx"
$rootFolder.Update()
LogWrite"successtosethomepage"
}
LogWrite"successtocreatepage$_"
}
$spWeb.Dispose()
}
catch
{
write-host"(ERROR:"$_.Exception.Message")"
LogWrite"failedtocreatepage"
LogWrite$_.Exception.Message
throw
}

}


b.创建文件夹

functionCreateFolder($webUrl,[Array]$folderNames){
$spWeb=Get-SPWeb$webUrl
$list=$spWeb.Lists["Pages"]
$folderNames|ForEach{
$folderName=$_
$folder=$list.Folders|where{$_.Name-eq$folderName}
if($folder-ne$null){
$list.Folders.DeleteItemById($folder.ID)
$list.Update()
}
$folder=$list.AddItem("",[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,$folderName)
$folder.Update()
$list.Update()
}
}



c.删除审批功能

functionRemoveApproval($webUrl,$listName,$workFlowName){
$web=Get-SPWeb$webUrl
try
{
$list=$web.Lists[$listName]
if(!($list-eq$null))
{
Write-Host"-DisablingModerationon"$listName
$list.EnableModeration=$false
$list.update()
$wa=$list.WorkflowAssociations.GetAssociationByName($workFlowName,[System.Globalization.CultureInfo]::CurrentCulture)
if(!($wa-eq$null))
{
Write-Host"-Removing"$wa.Name"from"$listName
$list.WorkflowAssociations.Remove($wa)
LogWrite"sucesstoremoveapproval"
}
}
}
catch{
LogWrite"failedtoremoveapproval"
LogWrite$_.Exception.Message
throw
}
$web.Dispose()
}



6.创建SecurityGroup

a.清除站点权限组

functionClearPermissionGroup($webUrl,$copyRoleAssignments)
{
try{
######Getthewebobjectthatrequiresthenewgroups
$web=Get-SPWeb$webUrl
######Ifthewebobjectiscurrentlyinheritingpermissionthenbreaktheinheritance
if($web.HasUniquePerm-eq$false)
{
$web.BreakRoleInheritance($copyRoleAssignments)
}
######Removeunnecessarygroups/usersfromthesitepermissionsforbasedsite
for($i=$web.RoleAssignments.Count–1;$i-ge0;$i--)
{
$name=$web.RoleAssignments.Groups[$i].Name
$web.RoleAssignments.Remove($i)
LogWrite"successtoremove$namepermissiongroup"
}

}
catch{
LogWrite"failedtoremove$groupNamepermissiongroup"
LogWrite$_.Exception.Message
throw
}
finally{
$web.Dispose()
}
}



b.创建安全组

####Createscuritygroups
$spBaseGroups=
@{
"SPMembers"="Contribute(NoDelete)";
"SPApprovers"="Approve";
"SPOwners"="FullControl";
"SPAdmins"="Admin";
"SPVisitors"="Read";
}
<preclass="html"name="code">####Createscuritygroups
functionCreateSecurityGroup($webUrl,$collection,$isGroup)
{
try{

#clearupexsitingsitegroup
if($isGroup-eq$true){
LogWrite"watingforclearingupsecuritygroupsin$webUrl"
ClearAllSecurityGroup$webUrl$collection
}

######Getthewebobjectthatrequiresthenewgroups
$web=Get-SPWeb$webUrl
$name=""
$role=""
$collectionEnumerator=$collection.GetEnumerator();
$collectionEnumerator|ForEach{
$name=$_.Key
$role=$_.Value

###Addgroup
if($isGroup-eq$true){
######Createthenewgroups
$web.SiteGroups.Add($_.Key,$web.Site.Owner,$null,"Usethisgrouptograntpeoplepermissionstothe$website")
$ownerGroup=$web.SiteGroups[$_.Key]

$ownerGroup.AllowMembersEditMembership=$true
$ownerGroup.Update()
LogWrite"groupnamed$nameaddedsuccess"
}

#####grantpermissiontogroup
if($_.Value-ne""-and$_.Value-ne$null-and$isGroup-eq$false){

if($web.HasUniquePerm-eq$false){
LogWrite"Thiswebdidn'thaveuniquepermission"
throw
return
}

$ownerGroup=$web.SiteGroups[$_.Key]
if($ownerGroup-ne$null){
######Createanewassignment(groupandpermissionlevelpair)whichwillbeaddedtothewebobject
$ownerGroupAssignment=new-objectMicrosoft.SharePoint.SPRoleAssignment($ownerGroup)

$_.Value|ForEach{
######Getthepermissionlevelstoapplytothenewgroups
$ownerRoleDefinition=$web.RoleDefinitions[$_]

######Assignthegroupstheappropriatepermissionlevel
$ownerGroupAssignment.RoleDefinitionBindings.Add($ownerRoleDefinition)
}

######Addthegroupswiththepermissionleveltothesite
$web.RoleAssignments.Add($ownerGroupAssignment)
LogWrite"roledefinitionnamed$roleaddedsuccessingroup$name"
}
else{
LogWrite"groupnamed$nameisnotexsiting"
throw
}

}
}

}
catch
{
LogWrite"groupnamed$nameaddedfailed"
LogWrite$_.Exception.Message
throw
}
finally{
$web.Update()
$web.Dispose()
}
}



c.添加用户到安全组

####Adduserstogroups

<preclass="html"name="code">$securityGroups=
@{
"SPMembers"=$("ADMembers");
"SPApprovers"=$("ADApprovers");
"SPOwners"=$("ADOwners");
"SPAdmins"=$("ADAdmins");
"SPVisitors"=$("ADVisitors");

}

functionAddADGroup($webUrl,[Object]$groups)
{
######Getthewebobjectthatrequiresthenewgroups
try
{
$web=Get-SPWeb$webUrl
$groupsEnumerator=$groups.GetEnumerator()
$groupsEnumerator|ForEach{
$groupName=$_.Key
$ownerGroup=$web.SiteGroups[$_.Key]
[Array]$usersAlias=$_.Value
$usersAlias|ForEach{
if($_-ne$null-and$_-ne"")
{
$userName=$_
$user=$web.Site.RootWeb.EnsureUser($_)
if($user-ne$null){
$ownerGroup.AddUser($user)
LogWrite"successtoaddtheuserorgroupnamed$_in$groupName"
}
else{
LogWrite"theuserorgroupnamed$_isnotexisting"
throw
}

}
}
$ownerGroup.Update()
}
}
catch
{
LogWrite$_.Exception.Message
throw
}
finally{
$web.Dispose()
}

}


d.list和items权限操作

####Addpermissiontolist
[Object]$listsBase=
@{
$("List1",“List11”)=@{"SPApproval"="Approve"};
$("List2")=@{"SPMember"="Contribute(NoDelete)";"SPVisitors"="Read";"SPMembers"="Contribute(NoDelete)";};
}

functionAddListPermission($webUrl,[Object]$lists,$isBreakRoleInheritance)
{
try{
$web=Get-SPWeb$webUrl
$listEnumerator=$lists.GetEnumerator()
$listEnumerator|ForEach{
$listInfo=$_
$listNames=$listInfo.Key
$listNames|ForEach{
$listName=$_
$list=$web.Lists.TryGetList($listName)
if($list-ne$null)
{
if($list.HasUniqueRoleAssignments-eq$true)
{
$list.ResetRoleInheritance()
}
$list.BreakRoleInheritance($isBreakRoleInheritance)

[Object]$groups=$listInfo.Value
$groupsEnumerator=$groups.GetEnumerator()
$groupsEnumerator|ForEach{
$groupInfo=$_
$groupName=$groupInfo.Key
$group=$web.SiteGroups[$groupName]

if($group-ne$null)
{
$assignment=New-ObjectMicrosoft.SharePoint.SPRoleAssignment($group)
$permission=$groupInfo.Value
$role=$web.RoleDefinitions[$permission]
$assignment.RoleDefinitionBindings.Add($role)
$list.RoleAssignments.Add($assignment)
}
else
{
LogWrite"groupnamed$groupNameisnotexisting"
throw
}
}
$list.Update()
LogWrite"listnamed$listNameadd$groupNamepermissionsuccess"

}
else
{
LogWrite"listnamed$listNameisnotexisting"
}
}

}
}
catch{
LogWrite$_.Exception.Message
throw
}
finally{
$web.Dispose()
}
}
[Object]$knowledgeLibraryItems=
@{
$("Sign")=@{"SPMembers"="Contribute"};
}

functionAddListItemsPermission($webUrl,$listName,[Object]$items,$isBreakRoleInheritance)
{
try{
$web=Get-SPWeb$webUrl
$list=$web.Lists.TryGetList($listName)
$itemsEnumerator=$items.GetEnumerator()
$itemsEnumerator|ForEach{
$itemInfo=$_
$itemNames=$itemInfo.Key
$itemNames|ForEach{
$itemName=$_

if($list-ne$null)
{
$item=$list.Items|Where{$_.Name-eq$itemName}
if($item-eq$null){
LogWrite"itemnamed$itemNameisnotexisting"
return
}

if($item.HasUniqueRoleAssignments-eq$true)
{
$item.ResetRoleInheritance()
}
$item.BreakRoleInheritance($isBreakRoleInheritance)

[Object]$groups=$itemInfo.Value
$groupsEnumerator=$groups.GetEnumerator()
$groupsEnumerator|ForEach{
$groupInfo=$_
$groupName=$groupInfo.Key
$group=$web.SiteGroups[$groupName]

if($group-ne$null)
{
$assignment=New-ObjectMicrosoft.SharePoint.SPRoleAssignment($group)
$permission=$groupInfo.Value
$role=$web.RoleDefinitions[$permission]
$assignment.RoleDefinitionBindings.Add($role)
$item.RoleAssignments.Add($assignment)
}
else
{
LogWrite"groupnamed$_.Keyisnotexisting(itemname$itemName)"
}
}
$item.Update()
LogWrite"itemnamed$itemNameadd$groupNamepermissionsuccess"

}
else
{
LogWrite"listnamed$listNameisnotexisting"
}
}

}
}
catch{
LogWrite$_.Exception.Message
throw
}
finally{
$web.Dispose()
}
}


e.创建roledefinition

functionCreateControl($webUrl){
$spWeb=get-spweb$webUrl
if($spWeb.RoleDefinitions["Admin"]-ne$null){
$spWeb.RoleDefinitions.Delete("Admin")
$spWeb.Update()
}
$spRoleDefinition=New-ObjectMicrosoft.SharePoint.SPRoleDefinition
$spRoleDefinition.Name="Admin"
$spRoleDefinition.Description="AdminisacustompermissionlevelbasedonControlpermissionlevel"
$spRoleDefinition.BasePermissions="FullMask"
$spWeb.RoleDefinitions.Add($spRoleDefinition)
$spWeb.Update()
$spWeb.Dispose()
LogWrite"successtocreateroledefinitionnamedAdmin"
}


7.其他函数

a.记录日志

$script_path=$myinvocation.mycommand.path
$script_folder=Split-Path$script_path-Parent
$Logfile=$script_folder+"\LOG.log"
FunctionLogWrite($logstring)
{
try
{
$time=get-date
$content=$time.ToShortDateString()+""+$time.Hour+":"+$time.Minute+":"+$time.Second+""+$logstring
Add-content$Logfile-value$content
write-host$logstring
}
catch
{
Add-content$Logfile-value$_.Exception.Message
write-host$_.Exception.Message
throw
}
}

b.metadata导入和导出

try{
LogWrite"starttoimportmetadataservice"
$proxyName="ManagedMetadataService"
$serviceName="ManagedMetadataService"
#$script_path=$myinvocation.mycommand.path
#$script_folder=Split-Path$script_path-Parent
#$filePath=$script_folder+"\Metadata.bak"

#GettheMetadataServiceApplication
$svc=Get-SPServiceApplication|?{$_.TypeName-eq"ManagedMetadataService"-and$_.DisplayName-eq$serviceName}

#UsethistoExport
Export-SPMetadataWebServicePartitionData$svc.Id-ServiceProxy$proxyName-Path$filePath
#Import-SPMetadataWebServicePartitionData$svc.Id-ServiceProxy$proxyName-Path$filePath-OverwriteExisting
LogWrite"successtoimportmetadataservice"
}
catch{
LogWrite"failedtoimportmetadataservice"
LogWrite$_.Exception.Message
throw
}

c.设置metadata为全局导航栏

functionUpdateNavigation($webUrl,$termStoreName,$termGroupName,$termSetName){
$web=Get-SPWeb$webUrl
$site=$web.Site
$navSettings=New-ObjectMicrosoft.SharePoint.Publishing.Navigation.WebNavigationSettings($web)
$taxSession=Get-SPTaxonomySession-Site$site
$termStore=$taxSession.TermStores[$termStoreName]
$termGroup=$termStore.Groups[$termGroupName]
$termSet=$termGroup.TermSets[$termSetName]
#QuickLaunch
#$navSettings.CurrentNavigation.Source=2
#$navSettings.CurrentNavigation.TermStoreId=$termStore.Id
#$navSettings.CurrentNavigation.TermSetId=$termSet.Id
#GlobalNavigation
$navSettings.GlobalNavigation.Source=2
$navSettings.GlobalNavigation.TermStoreId=$termStore.Id
$navSettings.GlobalNavigation.TermSetId=$termSet.Id

$navSettings.AddNewPagesToNavigation=$false
$navSettings.CreateFriendlyUrlsForNewPages=$false
$navSettings.Update()
LogWrite"Navigationupdatedsuccesfullyforsite$webUrl"
}

try{
LogWrite"starttoSetNavigationwithMetadataservice"
#UpdateNavigation$webUrl$termStoreName$termGroupName$termSetName
UpdateNavigation$webUrl"ManagedMetadataService""Navigation""NavTop"
}
catch{
LogWrite"failedtoSetNavigationwithMetadataservice"
LogWrite$_.Exception.Message
throw
}



#Approvethepageafterupdatingthepage
functionApprovalPage($pageRelativeUrl){
$page=$webUrl+$pageRelativeUrl
$web=Get-SPWeb$webUrl
$page|ForEach-Object{
$item=$web.GetListItem($_)
$item.File.Approve("Approvethepage")
LogWrite"Approved$pageRelativeUrl"
}
$web.Dispose()
}

#UpdatetheZoneandZoneIndexofthewebpart
functionUpdateWebPartPublish($webUrl,$pagePath,$name){
$pageUrl=$webUrl+$pagePath
$spWeb=Get-SPWeb$webUrl-ErrorActionStop

[Microsoft.SharePoint.Publishing.PublishingWeb]$pubWeb=[Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($spWeb)
$allowunsafeupdates=$spWeb.AllowUnsafeUpdates
$spWeb.AllowUnsafeUpdates=$true
$page=$spWeb.GetFile($pageUrl)

try{

if($page.Level-eq[Microsoft.SharePoint.SPFileLevel]::Checkout)
{
if($page.CheckedOutBy.UserLogin-ne$spWeb.CurrentUser.UserLogin)
{
$page.UndoCheckOut()
$page.CheckOut()
}
}
else
{
$page.CheckOut()
}

#InitialisetheWebpartmanagerforthespecifiedprofilepage.
$spWebPartManager=$spWeb.GetLimitedWebPartManager($pageUrl,[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
$wp=$spWebPartManager.WebParts|where{$_.Title-eq$name}
$spWebPartManager.MoveWebPart($wp,$leftZone,2)
$spWebPartManager.SaveChanges($wp)

#Checktoensurethepageischeckedoutbyyou,andifso,checkitin
if($page.CheckedOutBy.UserLogin-eq$spWeb.CurrentUser.UserLogin)
{
$page.CheckIn("PagecheckedinautomaticallybyPowerShellscript")
}

$page.Publish("Published")
$spWebPartManager.Web.Dispose()
$pubWeb.Close()
LogWrite"successtoadd$titlewebpart"
}

catch
{
$page.UndoCheckOut()
LogWrite"failedtoadd$titlewebpart"
LogWrite$_.Exception.Message

}

finally
{
$spWeb.Dispose()
}

}

#AddnewterminManagedMetadataService
functionAddMenuNavigation($siteUrl){
$spsite=$null
try{
$spsite=get-spsite$siteUrl
$taxonomySession=Get-SPTaxonomySession-Site$siteUrl
$termStore=$taxonomySession.TermStores["ManagedMetadataService"]
$termgroup=$termstore.groups["Navigation"]
$termset=$termgroup.TermSets["NavTop"]
$term=$termSet.Terms["BackofHouse"]
$term=$term.Terms["Policies&Procedures"]
$term=$term.CreateTerm("Forum",1033)
$navTerm=[Microsoft.SharePoint.Publishing.Navigation.NavigationTerm]::GetAsResolvedByWeb($term,$spsite.RootWeb,"GlobalNavigationTaxonomyProvider")
$term.SetLocalCustomProperty("_Sys_Nav_SimpleLinkUrl","/en-us/ComplianceForum")
$termStore.CommitAll()
LogWrite"successtoaddtargeturlForum"
}
catch{
LogWrite"$_.Exception.Message"
}
finally{
if($spsite-ne$null){
$spsite.Dispose()
}
}
}

#CreatecustompermissiondefinitionbasedonModerate
functionCreateModerate($webUrl){
$spWeb=get-spweb$webUrl
if($spWeb.RoleDefinitions["Moderate"]-ne$null){
LogWrite"TheModerateisexisting"
return
}
$spRoleDefinition=New-ObjectMicrosoft.SharePoint.SPRoleDefinition
$spRoleDefinition.Name="Moderate"
$spRoleDefinition.Description="ModerateisacustompermissionlevelbaseonoriginalModerate"
$spRoleDefinition.BasePermissions="ViewListItems,AddListItems,EditListItems,DeleteListItems,OpenItems,ViewVersions,DeleteVersions,CancelCheckout,ManagePersonalViews,ManageLists,ViewFormPages,Open,ViewPages,CreateSSCSite,BrowseDirectories,BrowseUserInfo,AddDelPrivateWebParts,UpdatePersonalWebParts,UseClientIntegration,UseRemoteAPIs,CreateAlerts,EditMyUserInfo"
$spWeb.RoleDefinitions.Add($spRoleDefinition)
$spWeb.Update()
$spWeb.Dispose()
LogWrite"successtocreateroledefinitionnamedModerate"
}






PS:未完待续。。。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: