Create Site Columns, Content Type and Add to Library using PowerShell


A good script to have for testing.

Add-PSSnapIn "Microsoft.SharePoint.Powershell"
#Get the site collection and web object
$siteColl = Get-SPSite -Identity "https://portal.contoso.com"
function Create-SiteColumnText ($siteColl, $CustomColumn)
{
    $rootWeb = $siteColl.RootWeb
    #Assign fieldXMLString variable with field XML for site column
    $fieldXMLString = "<Field Type='Text' Name='$CustomColumn'
    Description='Indicate date of last and next meeting and names of current members.'
    DisplayName='$CustomColumn'
    StaticName='$CustomColumn'
    Group='Custom Columns'
    Hidden='FALSE'
    Required='FALSE'
    Sealed='FALSE'
    ShowInDisplayForm='TRUE'
    ShowInEditForm='TRUE'
    ShowInListSettings='TRUE'
    ShowInNewForm='TRUE'></Field>"
    #See field XML on console
    #write-host $fieldXMLString
    #Create site column from XML string
    $rootWeb.Fields.AddFieldAsXml($fieldXMLString) 
    Write-Host "Column Added"
}

function Create-SiteColumnChoice ($siteColl, $CustomColumn)
{
    $rootWeb = $siteColl.RootWeb
    #Assign fieldXMLString variable with field XML for site column
    $fieldXMLString = "<Field Type='Choice' 
    Name='$CustomColumn'
    Description='Choice.'
    Format='Dropdown'
    DisplayName='$CustomColumn'
    StaticName='$CustomColumn'
    Group='Custom Columns'
    Hidden='FALSE'
    Required='FALSE'
    Sealed='FALSE'
    ShowInDisplayForm='TRUE'
    ShowInEditForm='TRUE'
    ShowInListSettings='TRUE'
    ShowInNewForm='TRUE'>
    <Default>Specification</Default>
                <CHOICES>
                  <CHOICE>Specification</CHOICE>
                  <CHOICE>Development</CHOICE>
                  <CHOICE>Test</CHOICE>
                  <CHOICE>Documentation</CHOICE>
                </CHOICES>
    </Field>"
    #See field XML on console
    #write-host $fieldXMLString
    #Create site column from XML string
    $rootWeb.Fields.AddFieldAsXml($fieldXMLString) 
    Write-Host "Column Added"
}


Create-SiteColumnText -siteColl $siteColl -CustomColumn "MyCustomColumn1"
Create-SiteColumnText -siteColl $siteColl -CustomColumn "MyCustomColumn2"
Create-SiteColumnText -siteColl $siteColl -CustomColumn "MyCustomColumn3"
Create-SiteColumnChoice -siteColl $siteColl -CustomColumn "MyCustomColumn4"

$web = $siteColl.RootWeb
$ctypeName = "MyCustomContentType"
$ctypeParent = $web.availablecontenttypes["Document"]
$ctype = new-object Microsoft.SharePoint.SPContentType($ctypeParent, $web.contenttypes, $ctypeName)
$web.contenttypes.add($ctype)
$field = $web.fields.getfield("MyCustomColumn1")
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
$ctype.fieldlinks.add($fieldLink)

$field = $web.fields.getfield("MyCustomColumn2")
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
$ctype.fieldlinks.add($fieldLink)

$field = $web.fields.getfield("MyCustomColumn3")
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
$ctype.fieldlinks.add($fieldLink)

$field = $web.fields.getfield("MyCustomColumn4")
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($field)
$ctype.fieldlinks.add($fieldLink)
$ctype.Update()

$Library =$Web.Lists["Documents"]
$Library.ContentTypesEnabled = $true

$Library.ContentTypes.Add($ctype);
$Library.Update()

Inventory SharePoint Sites – PowerShell


Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue

$SiteCollections = @()
$Data = Import-Csv -Path C:\Everything\SitesProfile.csv
if($Data)
{

    [string]$SiteUrls =""
    foreach($Site in $Data)
    {
         $SiteUrl = $Site.SiteUrl
         $sitecoll = New-Object Microsoft.SharePoint.SPSite($SiteUrl)   
         foreach ($web in $sitecoll.AllWebs) {
                    foreach ($list in $web.Lists) {
                        if ($list.Hidden) { continue }
                            $data = @{
                            "Site" = $sitecoll.Url
                            "Web" = $web.Url
                            "List" = $list.Title
                            "ItemCount" = $list.ItemCount
                            "LastModified" = $list.LastItemModifiedDate 
                            }
                            $List = New-Object PSObject -Property $data
                            $SiteCollections +=$List
                       
                            }
                    $web.Dispose();
                }
         $sitecoll.Dispose()
    }
}
#$SiteCollections | Out-GridView
#$SiteCollections | Export-Csv -NoTypeInformation -Path C:\Everything\Inventory.csv

Adding Users to Web App as Full Control


One of the most common issues I face while working with different environments is full control to all web applications in a SharePoint Farms.  The best way to tackle this issue for a team would be to create a AD Group and add the group to web application level using the same script but it is an issue where this method is not used so I faces issues browsing different web applications in different farms.  You can use the script below to fix this issues.

function Add-FullControl($UserName, $WebApp) 
{
    Write-Host "Adding $UserName as Full Control." -ForegroundColor Green
    $User = New-SPClaimsPrincipal -IdentityType WindowsSamAccountName -Identity $UserName
    $Policy = $WebApp.Policies.Add($User.ToEncodedString(), $UserName)   
    $Policy.PolicyRoleBindings.Add($WebApp.PolicyRoles.GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]::FullControl))   
    $WebApp.Update()
    Write-Host "Done for $UserName." -ForegroundColor Green
} 

foreach($WebApp in Get-SPWebApplication)
{
    $UserAccount = "contoso\sphelpdesk"
    Add-FullControl -UserName $UserAccount -WebApp $WebApp
}
Write-Host "All Done..." -ForegroundColor Green

Not a huge thing to do from UI but if you have big number of farms with many web apps this script will be handy.  The same script can be used for Cache Super User and Super Reader Accounts but minor changes to GetSpecialRole([Microsoft.SharePoint.Administration.SPPolicyRoleType]:: 🙂

Clearning up Large Lists and Recycle Bin with PowerShell


If you want to dump large lists quickly you can use batch delete script mentioend below.  Deleing items one by one in loop will take a lot of time.  Even if you delete the items they will get stuck in site collection recyle bin.  You can modify the script as needed.

Add-PSSnapin Microsoft.SharePoint.powerShell -ErrorAction SilentlyContinue 
$sitecollectionUrl = https://portal.contoso.com
$siteCollection = New-Object Microsoft.SharePoint.SPSite($sitecollectionUrl)
$web = $siteCollection.OpenWeb('Web') 

$list = $web.Lists["Logging List"] 

write-host("Logging List has : $list.ItemCount Items.") -ForegroundColor Yellow
write-host("Recyle Bin has : $siteCollection.RecycleBin.Count Items.") -ForegroundColor Yellow 

$itemCount = 0;
$listId = $list.ID;
[System.Text.StringBuilder]$batchXml = New-Object "System.Text.StringBuilder";
$batchXml.Append("<?xml version=`"1.0`" encoding=`"UTF-8`"?><Batch>");
$command = [System.String]::Format( "<Method><SetList>{0}</SetList><SetVar Name=`"ID`">{1}</SetVar><SetVar Name=`"Cmd`">Delete</SetVar></Method>", $listId, "{0}" ); 

$listItems = $list.Items
foreach ($item in $listItems)
{
    if($item -ne $null){$batchXml.Append([System.String]::Format($command, $item.ID.ToString())) | Out-Null;$itemCount++;}
} 

$batchXml.Append("</Batch>");
$itemCount; 

$web.ProcessBatchData($batchXml.ToString()) | Out-Null;Write-Host("Starting to Clear Site Collection Recyle Bin: $siteCollection.RecycleBin.Count") -ForegroundColor Yellow 
$siteCollection.RecycleBin.DeleteAll();
Write-Host("Cleared Log List and Site Collection Recyle Bin.")
$web.Dispose()
$siteCollection.Dispose()
 

Export All Sites and Sub Sites with Templates


Note: There are more simpler ways to do that but this script is more batch proess.

if((Get-PSSnapin -Name Microsoft.Sharepoint.PowerShell -ErrorAction SilentlyContinue) -eq $null) {  Add-PSSnapin Microsoft.Sharepoint.PowerShell } 

$outputFile = "E:\Scripts\Communityportal.csv"
$outputFileAll = "E:\Scripts\AllSitesHierarcy.csv"
$Sites = @(); 

$webApp = Get-SPWebApplication 

foreach($webApp in Get-SPWebApplication)
{
  Write-Host "Web Application : " + $webApp.Name 

  foreach($spSite in $webApp.Sites)
    { 
     if($spSite -ne $null)
      { 
       foreach ($spWeb in $spSite.AllWebs)
       {
           $TempalteID = $spWeb.WebTemplateId
           $Tempalte = $spWeb.WebTemplate
           write-host "Web Template:" $Tempalte  "| Web Template ID:" $TempalteID
           $csv = new-object PSObject
           add-member -InputObject $csv NoteProperty "WebURL" $spWeb.Url
           add-member -InputObject $csv NoteProperty "WebTemplate" $Tempalte
           add-member -InputObject $csv NoteProperty "WebTemplateId" $TempalteID
           $Sites +=$csv
           $spWeb.Dispose()
       } 
       $spSite.Dispose()     
       } 
     }
}
$Sites | Export-Csv -path $outputFileAll -notypeinformation
$Sites | ? WebTemplate -like "CommunityPortal*" | Export-Csv -path $outputFile -notypeinformation
$Sites | Out-GridView