首页 > 代码库 > Powershell 功能函数大全(Sharepoint 2013/2010)
Powershell 功能函数大全(Sharepoint 2013/2010)
Powershell 功能函数大全
说明: 本文章讲述powershell操作大全,是笔者多时积累完成。一步步从底层网站架构搭建,到网页内容的呈现, 均由powershell完成。 考虑到网站内容框架的移植,比如从开发环境到测试环境,再到产品环境,底层框架内容可由Powershell一键部署,这样更加方便以及可维护性。考虑到项目架构搭建的异同,初步分为以下步骤:
1. Poweshell 对 Site Column的完整操作
2. Powershell 对 Content Type的完整操作
3. Powershell 对 List 的完整操作
4. Powershell 对 Web Part(页面)操作
5. Powershell 对 Security Group操作
经过以上操作, 整个空网站就搭建成功。
1. Site Column的创建
a. 创建一般类型site column
function CreateSiteColumn($siteUrl, $columnName, $type, $required, $unique){ try{ $site = new-object Microsoft.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 "success to create sitecolumn $columnName" } catch { LogWrite "failed to create sitecolumn $columnName" LogWrite $_.Exception.Message throw } }
b. 创建RichText类型的site column
function CreateSiteColumn-Richtext($siteUrl, $columnName, $required, $unique){ try{ $site = new-object Microsoft.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 "success to create sitecolumn $columnName" } catch { LogWrite "failed to create sitecolumn $columnName" LogWrite $_.Exception.Message throw } }
c. 创建Calculated类型的site column
function CreateSiteColumn-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 "success to create sitecolumn $columnName" } catch { LogWrite "failed to create sitecolumn $columnName" LogWrite $_.Exception.Message throw } }
d. 创建Choice类型的site column
function CreateSiteColumn-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(" ", "") # Declare a new empty String collection $stringColl = new-Object System.Collections.Specialized.StringCollection # Add the choice fields from array to the string collection $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 "success to create sitecolumn $columnName" } catch { LogWrite "failed to create sitecolumn $columnName" LogWrite $_.Exception.Message throw } }
e. 创建Metadata 类型site column
function CreateSiteColumn-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(" ", "") #Create a taxonomy field $field = [Microsoft.SharePoint.Taxonomy.TaxonomyField]$rootWeb.Fields.CreateNewField($fieldType, $columnNameR); #Get a taxonomy session $session = new-object Microsoft.SharePoint.Taxonomy.TaxonomySession($site) #Get Term Store $termstore = $session.TermStores[$termStoreName] #Get Term Group $group = $termstore.Groups[$termGroupName] #Get Term Set $termSet= $group.TermSets[$termSetName] #populate newly created field $field.Sspid = $termSet.TermStore.Id $field.TermSetId = $termSet.Id if($termName -ne $null){ $terms = $termSet.GetAllTerms() # Get the Term using the name $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() #Update sp web $rootWeb.Update() $site.Dispose() LogWrite "success to create sitecolumn $columnName" } catch { LogWrite "failed to create sitecolumn $columnName" LogWrite $_.Exception.Message throw } }
2 . Content Type 的创建
a. 创建congtent type
function CreateContenType($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 | Select Name $parent = $rootWeb.AvailableContentTypes[$parentContentType] $contentType = New-Object Microsoft.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-Object Microsoft.SharePoint.SPFieldLink($fieldAdd) $ct.FieldLinks.Add($fieldLink) } } $ct.Update() $spSite.Dispose() LogWrite "success to create content type $contentTypeName" } catch{ LogWrite "faled to create content type $contentTypeName" LogWrite $_.Exception.Messag throw } }
b. 删除content type
function DeleteContenType($siteUrl){ try{ $spSite = Get-SPSite $siteUrl $rootWeb = $spSite.RootWeb $type = $rootWeb.ContentTypes $type | ForEach { if($_.Group -eq "Retail" -and $_.Name -ne "Retail Item Base" -and $_.Name -ne "Knowledge Asset"){ Write-Host $_.Name + $_.Id $type.Delete($_.Id) } } $rootWeb.Update() $rootWeb.Update() $spSite.Dispose() LogWrite "success to delete content type $contentTypeName" } catch{ LogWrite "faled to delete content type $contentTypeName" LogWrite $_.Exception.Messag throw } }
c. 更新Document set
function UpdateDocumentSet($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
function Add-SPList([string]$url, [string]$name, [string]$type) { try{ $spWeb = Get-SPWeb $url # Check list is exist or not $spList = $spWeb.Lists[$name] $templateType = $spWeb.ListTemplates[$type] if($spList -ne $null){ $spList.Delete() LogWrite "success to delete the list named $name " } [void]$spWeb.Lists.Add($name, "", $templateType) LogWrite "success to Add the list named $name" } catch{ LogWrite "failed to add list named $name" LogWrite $_.Exception.Message throw } finally{ $spWeb.Dispose() } }
b. 创建View
function Add-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 "list named $listName is not exsiting" 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 "succes add the list view named $viewName in list $listName" } catch{ LogWrite "failed to Add SPListView $listViewName in list $listName" LogWrite $_.Exception.Message throw } finally{ $spWeb.Dispose() } }
c. 添加site column到list
function Add-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 "success to add site column $fieldNames in list $listName" } else{ LogWrite "failed to add site column $fieldNames in list $listName for the list is noe existing" } } catch{ write-host "(ERROR : "$_.Exception.Message")" LogWrite "failed to add site column $fieldNames in list $listName" LogWrite $_.Exception.Message throw } finally{ $spWeb.Dispose() $spSite.Dispose() } }
d. 添加field到view
function AddViewField([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 "success to add list view field $fieldName in list $listName" } else{ LogWrite "The list $listName is not exiting in the site" throw } } catch{ write-host "(ERROR : "$_.Exception.Message")" LogWrite "failed to add list view field $fieldName n list $listName" LogWrite $_.Exception.Message throw } finally{ $spWeb.Dispose() } }
e. 添加content type到list
function AddContentTypeToList($siteUrl, $webUrl, $listName, $contentTypeName) { $spSite = Get-SPSite $siteUrl $spWeb = Get-SPWeb $webUrl $rootWeb = $spSite.rootweb $contentTypes = $rootWeb.ContentTypes try{ # Check list is exist or not $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 "success to add content type $contentTypeName in list $listName" } else{ $list.ContentTypes.Delete($listCT.Id) $list.Update() LogWrite "success to delete content type $contentTypeName in list $listName" $list.ContentTypes.Add($contentType) $list.Update() LogWrite "success to add content type $contentTypeName in list $listName" } } else{ LogWrite "The contentType $contentTypeName is not exiting in the site" throw } } else{ LogWrite "The list $listName is not existing in the site" throw } } catch{ LogWrite "failed to add content type $contentTypeName in list $listName" LogWrite $_.Exception.Message throw } finally{ $spWeb.Dispose() $spSite.Dispose() } }
f. 删除content type
function DeleteContentType($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 "success to delete content type $contentTypeName in list $listName" } else{ LogWrite "The contentType $contentTypeName is not exiting in the list $listName" } } else{ LogWrite "The list $listName is not exiting in the site" } } else{ LogWrite "The contentType $contentTypeName is not exiting in the site" } } catch{ write-host "(ERROR : "$_.Exception.Message")" LogWrite "failed to delete list content type $contentTypeName in list $listName" LogWrite $_.Exception.Message throw } finally{ $spWeb.Dispose() $spSite.Dispose() } }
g. 改变 content type in list items
function ChangeContentType($webUrl, $listName, $oldContentType, $newContentType){ $web=Get-SPWeb $webUrl $rootWeb = $web.Site.RootWeb $folderFilter = $rootWeb.ContentTypes[$newContentType] $folder = $rootWeb.ContentTypes[$oldContentType] #$query.ViewXml = "<Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>1</Value></Eq>" $query = New-Object Microsoft.SharePoint.SPQuery $query.ViewAttributes = "Scope=RecursiveAll" $list = $web.Lists[$listName] $items = $list.GetItems($query) foreach($item in $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. 添加web part
a. 添加web part
function AddWebPartPublish($webUrl, $pagePath, $listName, $listViewName, $title, $jsLink, $webpartZone, $index) { $pageUrl = $webUrl + $pagePath $spWeb = Get-SPWeb $webUrl -ErrorAction Stop [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 "lack of view named $listViewName in list $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() } #Initialise the Web part manager for the specified profile page. $spWebPartManager = $spWeb.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared) $ListViewWebPart = New-Object Microsoft.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 "The list named $listName is not existing" return } #Check to ensure the page is checked out by you, and if so, check it in if ($page.CheckedOutBy.UserLogin -eq $spWeb.CurrentUser.UserLogin) { $page.CheckIn("Page checked in automatically by PowerShell script") } $page.Publish("Published") $pubWeb.Close() LogWrite "success to add $title webpart" } catch { $page.UndoCheckOut() LogWrite "failed to add $title webpart" LogWrite $_.Exception.Message } finally { #$spWebPartManager.Dispose() $spWeb.Dispose() } }
b. 删除页面上所有web part
function RemoveWebPart($siteUrl, $pagePath) { $pageUrl = $siteUrl + $pagePath $spWeb = Get-SPWeb $siteUrl -ErrorAction Stop [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 "Page has already been checked out " } else { $SPWeb.CurrentUser.LoginName $page.UndoCheckOut() $page.CheckOut() write-host "Check out the page override" } } else { $page.CheckOut() write-host "Check out the page" } try{ #Initialise the Web part manager for the specified profile page. $spWebPartManager = $spWeb.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared) $flag = 0 #Circle all the Webparts in the specified page foreach ($webpart in $spWebPartManager.WebParts) { try{ $spWebPartManager.DeleteWebPart($spWebPartManager.WebParts[$webpart.ID]) $spWebPartManager.SaveChanges($webpart) } catch{ write-host "(ERROR : "$_.Exception.Message")" } } #Check to ensure the page is checked out by you, and if so, check it in if ($page.CheckedOutBy.UserLogin -eq $spWeb.CurrentUser.UserLogin) { $page.CheckIn("Page checked in automatically by PowerShell script") Write-Output "Page has been checked in" } $page.Publish("Published") Write-Output "Page has been published success" $pubWeb.Close() $spWeb.Update() } catch { write-host "(ERROR : "$_.Exception.Message")" } finally { $spWeb.Dispose() } }
c. 添加content editor web part
function AddContentEditorWebPart($webUrl, $pagePath, $title, $webpartZone, $index, $content){ $pageUrl = $webUrl + $pagePath $spWeb = Get-SPWeb $webUrl -ErrorAction Stop [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() } #Initialise the Web part manager for the specified profile page. $spWebPartManager = $spWeb.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared) $ListViewWebPart = New-Object Microsoft.SharePoint.WebPartPages.ContentEditorWebPart $listViewWebPart.Title = $title $docXml = New-Object System.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) #Check to ensure the page is checked out by you, and if so, check it in if ($page.CheckedOutBy.UserLogin -eq $spWeb.CurrentUser.UserLogin) { $page.CheckIn("Page checked in automatically by PowerShell script") } $page.Publish("Published") $pubWeb.Close() LogWrite "success to add $listName webpart" } catch { $page.UndoCheckOut() LogWrite "failed to add $listName webpart" LogWrite $_.Exception.Message } finally { $spWeb.Dispose() } }
d.添加filter web part connections
function AddSPWebPartConnections($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 "the webpart named $listViewTitle or $filterTitle is not existing " $page.UndoCheckOut() return } $conWP = $wpManager.GetConsumerConnectionPoints($webpartListView)["DFWP Filter Consumer ID"] $provWP = $wpManager.GetProviderConnectionPoints($webpartFilter)[0] [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") $trans = New-Object Microsoft.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) #Check to ensure the page is checked out by you, and if so, check it in if ($page.CheckedOutBy.UserLogin -eq $web.CurrentUser.UserLogin) { $page.CheckIn("Page checked in automatically by PowerShell script") } $page.Publish("Published") $pubWeb.Close() LogWrite "Success to add Connecntion of Filter webpart" } catch { $page.UndoCheckOut() LogWrite "failed to add $ForumListName webpart" LogWrite $_.Exception.Message } finally { $web.Dispose() } }
e. 天津自定义web part
function AddBoxWebpart($webUrl, $pagePath, $zone, $index, $title, $listName,$titleUrl) { $pageUrl = $webUrl + $pagePath $spWeb = Get-SPWeb $webUrl -ErrorAction Stop $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["Web Part Gallery"] $webpart=$webPartGallery.Items | ? { $_.Name -eq "StorePortal2014_Box.webpart"} $webpartmanager=$topWeb.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared) $errorMsg = "" $xmlReader = New-Object System.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); #Check to ensure the page is checked out by you, and if so, check it in if ($page.CheckedOutBy.UserLogin -eq $spWeb.CurrentUser.UserLogin) { $page.CheckIn("Page checked in automatically by PowerShell script") } $page.Publish("Published") $pubWeb.Close() LogWrite "Success to add $listName webpart" } catch { $page.UndoCheckOut() LogWrite "failed to add $listName webpart" LogWrite $_.Exception.Message } finally { $topWeb.Dispose() $spWeb.Dispose() } }
5. 根据不同layout添加页面
a. 创建页面
function CreatePage($webUrl, [Array] $pageNames, $layout, $folderName){ try{ $spWeb = Get-SPWeb $webUrl $list = $spWeb.Lists["Pages"] #Get Publishing Web $pubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($spWeb) #Finds the appropriate page layout #SpDesktopV2HomePage.aspx #SpDesktopV2TermPage.aspx #SpDesktopV2OnePartZone.aspx $layout = $pubWeb.GetAvailablePageLayouts() | Where { $_.Name -eq $layout} $query = new-object Microsoft.SharePoint.SPQuery $query.ViewAttributes = "Scope='Recursive'" if($folderName -ne $null){ $query.Folder = $list.RootFolder.SubFolders[$folderName] } $pages = $pubWeb.GetPublishingPages($query) $pageNames | Foreach { #Create the page; $page = $pages.Add($_, $layout) #Check in Page $page.CheckIn("Cretae page") $page.ListItem.File.Publish("Publish Comment") if($_ -eq "Home.aspx"){ #Set new page to be the welcome (home page) $rootFolder = $spWeb.RootFolder $rootFolder.WelcomePage = "Pages/home.aspx" $rootFolder.Update() LogWrite "success to set home page" } LogWrite "success to create page $_" } $spWeb.Dispose() } catch { write-host "(ERROR : "$_.Exception.Message")" LogWrite "failed to create page" LogWrite $_.Exception.Message throw } }
b. 创建文件夹
function CreateFolder($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. 删除审批功能
function RemoveApproval($webUrl, $listName, $workFlowName){ $web = Get-SPWeb $webUrl try { $list = $web.Lists[$listName] if(!($list -eq $null)) { Write-Host "- Disabling Moderation on" $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 "sucess to remove approval" } } } catch{ LogWrite "failed to remove approval" LogWrite $_.Exception.Message throw } $web.Dispose() }
6. 创建Security Group
a. 清除站点权限组
function ClearPermissionGroup($webUrl, $copyRoleAssignments) { try{ ###### Get the web object that requires the new groups $web = Get-SPWeb $webUrl ###### If the web object is currently inheriting permission then break the inheritance if ($web.HasUniquePerm -eq $false) { $web.BreakRoleInheritance($copyRoleAssignments) } ###### Remove unnecessary groups/users from the site permissions for based site for ($i = $web.RoleAssignments.Count – 1; $i -ge 0; $i--) { $name = $web.RoleAssignments.Groups[$i].Name $web.RoleAssignments.Remove($i) LogWrite "success to remove $name permission group" } } catch{ LogWrite "failed to remove $groupName permission group" LogWrite $_.Exception.Message throw } finally{ $web.Dispose() } }
b. 创建安全组
####Create scurity groups $spBaseGroups = @{ "SP Members" ="Contribute(No Delete)"; "SP Approvers" = "Approve"; "SP Owners" = "Full Control"; "SP Admins" = "Admin"; "SP Visitors" = "Read"; } <pre class="html" name="code">####Create scurity groups function CreateSecurityGroup($webUrl, $collection, $isGroup ) { try{ # clear up exsiting site group if($isGroup -eq $true){ LogWrite "wating for clearing up security groups in $webUrl" ClearAllSecurityGroup $webUrl $collection } ###### Get the web object that requires the new groups $web = Get-SPWeb $webUrl $name = "" $role = "" $collectionEnumerator = $collection.GetEnumerator(); $collectionEnumerator | ForEach{ $name = $_.Key $role = $_.Value ### Add group if($isGroup -eq $true){ ###### Create the new groups $web.SiteGroups.Add($_.Key, $web.Site.Owner, $null, "Use this group to grant people permissions to the $web site") $ownerGroup = $web.SiteGroups[$_.Key] $ownerGroup.AllowMembersEditMembership = $true $ownerGroup.Update() LogWrite "group named $name added success" } ##### grant permission to group if($_.Value -ne "" -and $_.Value -ne $null -and $isGroup -eq $false){ if ($web.HasUniquePerm -eq $false){ LogWrite "This web didn't have unique permission" throw return } $ownerGroup = $web.SiteGroups[$_.Key] if($ownerGroup -ne $null){ ###### Create a new assignment (group and permission level pair) which will be added to the web object $ownerGroupAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($ownerGroup) $_.Value | ForEach{ ###### Get the permission levels to apply to the new groups $ownerRoleDefinition = $web.RoleDefinitions[$_] ###### Assign the groups the appropriate permission level $ownerGroupAssignment.RoleDefinitionBindings.Add($ownerRoleDefinition) } ###### Add the groups with the permission level to the site $web.RoleAssignments.Add($ownerGroupAssignment) LogWrite "roledefinition named $role added success in group $name" } else{ LogWrite "group named $name is not exsiting" throw } } } } catch { LogWrite "group named $name added failed" LogWrite $_.Exception.Message throw } finally{ $web.Update() $web.Dispose() } }
c. 添加用户到安全组
#### Add users to groups <pre class="html" name="code"> $securityGroups = @{ "SP Members" =$("AD Members"); "SP Approvers" =$( "AD Approvers"); "SP Owners" = $("AD Owners"); "SP Admins" = $("AD Admins"); "SP Visitors" =$( "AD Visitors"); } function AddADGroup($webUrl, [Object] $groups) { ###### Get the web object that requires the new groups 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 "success to add the user or group named $_ in $groupName" } else{ LogWrite "the user or group named $_ is not existing" throw } } } $ownerGroup.Update() } } catch { LogWrite $_.Exception.Message throw } finally{ $web.Dispose() } }
d. list 和 items 权限操作
#### Add permission to list
[Object] $listsBase = @{ $("List 1", “List11”) = @{"SP Approval"="Approve"}; $("List2") = @{"SP Member"= "Contribute(No Delete)";"SP Visitors" = "Read";"SP Members" ="Contribute(No Delete)";}; } function AddListPermission($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-Object Microsoft.SharePoint.SPRoleAssignment($group) $permission = $groupInfo.Value $role = $web.RoleDefinitions[$permission] $assignment.RoleDefinitionBindings.Add($role) $list.RoleAssignments.Add($assignment) } else { LogWrite "group named $groupName is not existing" throw } } $list.Update() LogWrite "list named $listName add $groupName permission success" } else { LogWrite "list named $listName is not existing" } } } } catch{ LogWrite $_.Exception.Message throw } finally{ $web.Dispose() } } [Object] $knowledgeLibraryItems = @{ $("Sign") = @{"SP Members"="Contribute"}; } function AddListItemsPermission($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 "item named $itemName is not existing" 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-Object Microsoft.SharePoint.SPRoleAssignment($group) $permission = $groupInfo.Value $role = $web.RoleDefinitions[$permission] $assignment.RoleDefinitionBindings.Add($role) $item.RoleAssignments.Add($assignment) } else { LogWrite "group named $_.Key is not existing(item name $itemName)" } } $item.Update() LogWrite "item named $itemName add $groupName permission success" } else { LogWrite "list named $listName is not existing" } } } } catch{ LogWrite $_.Exception.Message throw } finally{ $web.Dispose() } }
e. 创建role definition
function CreateControl($webUrl){ $spWeb = get-spweb $webUrl if($spWeb.RoleDefinitions["Admin"] -ne $null){ $spWeb.RoleDefinitions.Delete("Admin") $spWeb.Update() } $spRoleDefinition = New-Object Microsoft.SharePoint.SPRoleDefinition $spRoleDefinition.Name = "Admin" $spRoleDefinition.Description = "Admin is a custom permission level based on Control permission level" $spRoleDefinition.BasePermissions = "FullMask" $spWeb.RoleDefinitions.Add($spRoleDefinition) $spWeb.Update() $spWeb.Dispose() LogWrite "success to create role definition named Admin" }
7. 其他函数
a. 记录日志
$script_path = $myinvocation.mycommand.path $script_folder = Split-Path $script_path -Parent $Logfile = $script_folder + "\LOG.log" Function LogWrite($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 "start to import metadata service" $proxyName = "Managed Metadata Service" $serviceName = "Managed Metadata Service" #$script_path = $myinvocation.mycommand.path #$script_folder = Split-Path $script_path -Parent #$filePath = $script_folder + "\Metadata.bak" #Get the Metadata Service Application $svc = Get-SPServiceApplication | ?{$_.TypeName -eq "Managed Metadata Service" -and $_.DisplayName -eq $serviceName} #Use this to Export Export-SPMetadataWebServicePartitionData $svc.Id -ServiceProxy $proxyName -Path $filePath #Import-SPMetadataWebServicePartitionData $svc.Id -ServiceProxy $proxyName -Path $filePath -OverwriteExisting LogWrite "success to import metadata service" } catch{ LogWrite "failed to import metadata service" LogWrite $_.Exception.Message throw }
c. 设置metadata为全局导航栏
function UpdateNavigation($webUrl,$termStoreName,$termGroupName,$termSetName){ $web= Get-SPWeb $webUrl $site = $web.Site $navSettings = New-Object Microsoft.SharePoint.Publishing.Navigation.WebNavigationSettings($web) $taxSession = Get-SPTaxonomySession -Site $site $termStore = $taxSession.TermStores[$termStoreName] $termGroup = $termStore.Groups[$termGroupName] $termSet = $termGroup.TermSets[$termSetName] #Quick Launch #$navSettings.CurrentNavigation.Source = 2 #$navSettings.CurrentNavigation.TermStoreId = $termStore.Id #$navSettings.CurrentNavigation.TermSetId = $termSet.Id #Global Navigation $navSettings.GlobalNavigation.Source = 2 $navSettings.GlobalNavigation.TermStoreId = $termStore.Id $navSettings.GlobalNavigation.TermSetId = $termSet.Id $navSettings.AddNewPagesToNavigation = $false $navSettings.CreateFriendlyUrlsForNewPages = $false $navSettings.Update() LogWrite "Navigation updated succesfully for site $webUrl" } try{ LogWrite "start to Set Navigation with Metadata service" #UpdateNavigation $webUrl $termStoreName $termGroupName $termSetName UpdateNavigation $webUrl "Managed Metadata Service" "Navigation" "NavTop" } catch{ LogWrite "failed to Set Navigation with Metadata service" LogWrite $_.Exception.Message throw }
PS:未完待续。。。
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。