Monday, March 2, 2015

Get Site information using PowerShell Script SharePoint 2013

With attached gallery PowerShell Script, you can get the site collection information which include Content DB details, count of current sub sites, and also size of each sub site, site collection and content DB.

The output of file is saved in CSV format, which you can save it to any defined path.

The script contains 5 functions, the main function is GetGeneralInfo which generates all site information, it takes site URLS and output file path as parameter.


[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

function GetWebSizes ($StartWeb)
{
    $web = Get-SPWeb $StartWeb
    [long]$total = 0
    $total += GetWebSize -Web $web
    $total += GetSubWebSizes -Web $web
    $totalInMb = ($total/1024)/1024
    $totalInMb = "{0:N2}" -f $totalInMb
    $totalInGb = (($total/1024)/1024)/1024
    $totalInGb = "{0:N2}" -f $totalInGb
    #write-host "Total size of all sites below" $StartWeb "is" $total "Bytes,"
    #write-host "which is" $totalInMb "MB or" $totalInGb "GB"
    "Total size for all sites in Bytes  `t $($total) Bytes" | Out-File $OutputFile -Append
    "Total size for all sites in MB `t $($totalInMb) MB" | Out-File $OutputFile -Append
    "Total size for all sites in MB `t $($totalInGb) GB" | Out-File $OutputFile -Append

    $web.Dispose()
}
function GetWebSize ($Web)
{
    [long]$subtotal = 0
    foreach ($folder in $Web.Folders)
    {
        $subtotal += GetFolderSize -Folder $folder
    }
    #write-host "Site" $Web.Title "is" $subtotal "KB"
    "Site $($Web.Title) `t $($subtotal) KB" | Out-File $OutputFile -Append
    return $subtotal
}
function GetSubWebSizes ($Web)
{
    [long]$subtotal = 0
    foreach ($subweb in $Web.GetSubwebsForCurrentUser())
    {
        [long]$webtotal = 0
        foreach ($folder in $subweb.Folders)
        {
            $webtotal += GetFolderSize -Folder $folder
        }
        #write-host "Site" $subweb.Title "is" $webtotal "Bytes"
        "Site $($subweb.Title) `t $($webtotal) Bytes" | Out-File $OutputFile -Append
        $subtotal += $webtotal
        $subtotal += GetSubWebSizes -Web $subweb
    }
    return $subtotal
}

function GetFolderSize ($Folder)
{
    [long]$folderSize = 0
    foreach ($file in $Folder.Files)
    {
        $folderSize += $file.Length;
    }
    foreach ($fd in $Folder.SubFolders)
    {
        $folderSize += GetFolderSize -Folder $fd
    }
    return $folderSize
}

Function GetGeneralInfo($siteUrl, $OutputFile)
{


#Write CSV- TAB Separated File) Header
"Name `t Value" | out-file $OutputFile

$ContentDB =  Get-SPContentDatabase -site $siteUrl
$ContentDatabaseSize = [Math]::Round(($ContentDatabase.disksizerequired/1GB),2)

"Database Name  `t $($ContentDB.Name)" | Out-File $OutputFile -Append
"Database ID  `t $($ContentDB.ID)" | Out-File $OutputFile -Append
"Site count `t $($ContentDB.CurrentSiteCount)" | Out-File $OutputFile -Append
"Site count `t $($ContentDB.MaximumSiteCount)" | Out-File $OutputFile -Append
"Can Migrate `t $($ContentDB.CanMigrate)" | Out-File $OutputFile -Append
"Content DB Size `t $($ContentDatabaseSize) GB" | Out-File $OutputFile -Append
"Database Servername `t $($ContentDB.Server)" | Out-File $OutputFile -Append
"Connection String `t $($ContentDB.DatabaseConnectionString)" | Out-File $OutputFile -Append
"Display Name `t $($ContentDB.DisplayName)" | Out-File $OutputFile -Append
"Schema `t $($ContentDB.SchemaVersionXml)" | Out-File $OutputFile -Append


GetWebSizes -StartWeb $siteUrl
}


GetGeneralInfo "http://spFarm" "C:\GeneralInfo.csv"

Find Lists or Libraries Using a Content Type in SharePoint with PowerShell

The following PowerShell script will loop through all the lists in a given site and look for a particular content type.  This is useful if you ever need to report on how many lists are using a content type, or you're just curious.

This script takes 2 arguments:

    Web URL - This is a fully qualified URL to the site.
    Content Type Name - This is the content type name.

So using the script would look like the following:

    Find-Content-Types.ps1 "http://SPURL/SITE" "CONTENT TYPE NAME"


############################################################################### 
##  ADD IN SHAREPOINT SNAP IN IF NOT ALREADY LOADED ## 
############################################################################### 
 
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) { 
    Add-PSSnapin "Microsoft.SharePoint.PowerShell" 
}


############################################################################### 
##  SET VARIABLES FROM ARGUMENTS ## 
############################################################################### 

$webUrl = $args[0]
$ctName = $args[1]

# Varibale to hold document count
$count = 0


############################################################################### 
##  PERFORM SEARCH ## 
############################################################################### 

# Get site instance
$site = get-spsite $webUrl

# Formatting
Write-Host ""
Write-Host "Starting search...."
Write-Host ""

# Loop through each web in site, then each list
foreach ($web in $site.AllWebs)
 {
   foreach ($lst in $web.lists)
   {
     foreach ($ctype in $lst.ContentTypes)
     {
           if ($ctype.Name -eq $ctName)
           {
        Write-Host $lst.DefaultViewUrl -ForegroundColor Yellow
        $count++
    }
     }
   }
   $web.Dispose()
 }

# Formatting
Write-Host ""
Write-Host "Found $count lists using the content type '$ctName'." -ForegroundColor Green

Annual Review of Documents Using PowerShell in SharePoint

In your SharePoint travels you may come across a requirement to have users review documents based on a timeframe.  For instance, the requirement may say something like:
"Users must review documents every 12 months to ensure
content is correct and up to date. Etc, etc."
This can be accomplished in a number of different ways in SharePoint, but in this script will accomplish this using PowerShell.  This demo will show you how to
query a document library for documents that fall within a date range and then notify the document's owner that they must review the document.

###############################################################################
##  ADD IN SHAREPOINT SNAP IN IF NOT ALREADY LOADED ##
###############################################################################


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


###############################################################################
##  VARIABLES ##
###############################################################################


$webUrl = "http://sp2010"
$listDisplayName = "Annual Review Documents"
$dateColumnInternalName = "Review_x0020_Date"
$ownerColumnInternalName = "Document_x0020_Owner"
$reviewDateDaysOut = 30
$startDateRangeDays = 29
$endDateRangeDays = 31
$smtpServer = "191.168.1.1"


$emailFromAddress = "annualreview@dev.com"
$emailSubjectLine = "Annual Review Documents Notification"

# DO NOT CHANGE THE FOLLOWING VARIABLES!
$dateToStringFormat = "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"
$logTextFileName = ".\log-" + (Get-date).ToString($dateToStringFormat) + ".txt" -replace " ","-" -replace ":","-"
$reviewDate = (Get-date).AddDays($reviewDateDaysOut).ToShortDateString()

$viewFilter = "?FilterField1=" + $dateColumnInternalName + "&FilterValue1=" + $reviewDate


###############################################################################
##  FUNCTIONS ##
###############################################################################


# Sends an email to the specified address
function SendEmail($ownerEmail, $docLibraryViewUrl, $documentName) {
    try {
          $smtp = new-object Net.Mail.SmtpClient($smtpServer)


        $msg = EmailStructure $ownerEmail $docLibraryViewUrl
 $documentUrl
          $smtp.Send($msg)

        $emailSentMessage = "Email sent to " + $ownerEmail
        AppendLogMessage $emailSentMessage
    }
    catch {
        Write-Host "Error sending email, check log file!" -ForegroundColor Red
        AppendLogMessage $error[0]
    }
}

# Builds the email message that will be sent
function EmailStructure($to, $docLibraryViewUrl
) {


      $msg = new-object Net.Mail.MailMessage

 
      $msg.IsBodyHtml = $true

      $msg.From = $emailFromAddress
      $msg.To.Add($to)
      $msg.Subject = $emailSubjectLine
      $msg.Body = "<html><body><b>Review items for $listDisplayName<br /><br /></b>The following document ($documentName) has a review date of $reviewDate.<br /><br />Click <a href = '"+ $docLibraryViewUrl + $viewFilter +"'>here</a> to review all documents which have a review date on $reviewDate.</body></html>"


     return $msg

}


# Appends text to the log message
function AppendLogMessage($text) {
    Add-Content $logTextFileName $text"`r" -Encoding UTF8
}


###############################################################################
##  CREATE LOG FILE ##
###############################################################################


# Creating base file to append to, adding a new line for readability
"Log file created." >> $logTextFileName
AppendLogMessage " "


###############################################################################
##  WEB AND DOCUMENT LIBRARY ##
###############################################################################


# Get the access to SP lib, open it
$web = Get-SPWeb $webUrl
$docLib = $web.Lists[$listDisplayName]


###############################################################################
##  SET DATE RANGE ##
###############################################################################


# Set the date range
$reviewStartDate = (Get-date).AddDays($startDateRangeDays).ToString($dateToStringFormat)
$reviewEndDate = (Get-date).AddDays($endDateRangeDays).ToString($dateToStringFormat)

# Write out the dates we're looking for
$dateRangeText = "INFO: Searching for documents with review dates between " + $reviewStartDate + " - " + $reviewEndDate
Write-Host $dateRangeText -ForegroundColor Green
AppendLogMessage $dateRangeText


###############################################################################
##  QUERY THE DOCUMENT LIBRARY ##
###############################################################################


# Build the SPQuery
$camlQuery = '<Where><And><Gt><FieldRef Name="' + $dateColumnInternalName + '" /><Value Type="DateTime" IncludeTimeValue="True">' + $reviewStartDate + '</Value></Gt><Lt><FieldRef Name="' + $dateColumnInternalName + '" /><Value Type="DateTime" IncludeTimeValue="True">' + $reviewEndDate + '</Value></Lt></And></Where>'
$spQuery = new-object Microsoft.SharePoint.SPQuery
$spQuery.Query = $camlQuery
$spListItems = $docLib.GetItems($spQuery)

# Write out the number of documents found
$docFoundText = "INFO: Found " + $spListItems.Count + " document(s)."
Write-Host $docFoundText -ForegroundColor Green
AppendLogMessage $docFoundText


###############################################################################
##  PROCESS DOCUMENTS AND SEND EMAILS ##
###############################################################################


# Log start of processing
$beginProcessingText = "INFO: Start processing documents."
Write-Host $beginProcessingText -ForegroundColor Green
AppendLogMessage $beginProcessingText

# Loop through items and write out info
foreach ($item in $spListItems) {
   
    # Get the SPUser object from the column
    $spFieldUser = [Microsoft.SharePoint.SPFieldUser]$item.Fields.GetField($ownerColumnInternalName);
    $spFieldUserValue = [Microsoft.SharePoint.SPFieldUserValue]$spFieldUser.GetFieldValue($item[$ownerColumnInternalName].ToString());
    $user = $spFieldUserValue.User;
   
    # Get the user email to test for null/empty
    $userEmail = user.Email

    # If the User's email is present send the email, otherwise log the error
    if ($userEmail) {
        # Build URL for item
        $docLibraryViewUrl = $web.Url + "/" + $docLib.DefaultView.Url

        $ownerDocEmail = "INFO: Document '" + $item.Name + "' has owner " + $userEmail
        AppendLogMessage $ownerDocEmail
        SendEmail $userEmail $docLibraryViewUrl $item.Name
    }
    else {
        $emptyDocEmail = "ERROR: No email is set for '" + $item.Name + "' with document owner: " + $user.DisplayName
        Write-Host $emptyDocEmail -ForegroundColor Red
        AppendLogMessage $emptyDocEmail
    }
}


###############################################################################
##  CLEAN UP ##
###############################################################################

# Log end of processing
$endProcessingText = "INFO: Finished processing documents."
Write-Host $endProcessingText -ForegroundColor Green
AppendLogMessage $endProcessingText

# Dispose of the web object
$web.Dispose()

SharePoint PowerShell script to cleanup all recycle bins in a site collection

This PowerShell script will take a site collection URL as input and will then itterate through each sub web in the site collection, clearing it's recycle bin before finally clearing the site collection recycle bin at the end.
This script is very useful if you're moving site collections around after mass item activity, such as migrations.  Running this script against your site collection will cleanup space in the database so it can be de-bloated from it's post migration state.


[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint");
$url = $args[0];
$site = new-object microsoft.sharepoint.spsite($url);
for ($i=0;$i -lt $site.allwebs.count;$i++)
{
  write-host $site.allwebs[$i].url "...deleting" $site.allwebs[$i].recyclebin.count "item(s).";
  $site.allwebs[$i].recyclebin.deleteall();
}
write-host $site.url "...deleting" $site.recyclebin.count "item(s).";
$site.recyclebin.deleteall();
$site.dispose();


Delete-Site-Recycle-Bin.ps1 http://MySharePointSiteCollectionURL

Get detail report of all Documents in SharePoint site using Powershell

[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Portal, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")
[System.Reflection.Assembly]::Load("System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")

function Get-DocInventory([string]$siteUrl) {
$site = New-Object Microsoft.SharePoint.SPSite $siteUrl
foreach ($web in $site.AllWebs) {
foreach ($list in $web.Lists) {
if ($list.BaseType -ne “DocumentLibrary”) {
continue
}

foreach ($item in $list.Items) {
$data = @{
"Site" = $site.Url
"Web" = $web.Url
"list" = $list.Title
"Item ID" = $item.ID
"Item URL" = $item.Url
"Item Title" = $item.Title
"Item Created" = $item["Created"]
"Item Modified" = $item["Modified"]
"Created By" = $item["Author"]
"Modified By" = $item["Editor"]
"File Size" = $item.File.Length/1KB
"File Size (MB)" = $item.File.Length/1MB
}
New-Object PSObject -Property $data
}
}
$web.Dispose();
}
$site.Dispose()
}

Get-DocInventory "http://sp2013" | Out-GridView
Get-DocInventory "http://sp2013" | Export-Csv -NoTypeInformation -Path "c:\Document_Detail_Report.csv"

Download SharePoint 2013 Pre-Requisites for Windows Server 2012

# This commands script file creates a new BITS transfer job that downloads all Sharepoint 2013 Prerequisites files for Windows Server 2012

$DestinationFolder = Read-Host -Prompt "Please enter the destination path for Sharepoint 2013 Prerequisites files"

# Note: The Prerequisite Files URLs are subject to change at Microsoft's discretion - check http://technet.microsoft.com/en-us/library/cc262485(v=office.15).aspx and update the links.
$FilesUrlList = (
        "http://download.microsoft.com/download/9/1/3/9138773A-505D-43E2-AC08-9A77E1E0490B/1033/x64/sqlncli.msi", # SQL Server 2008 R2 SP1 Native Client
        "http://download.microsoft.com/download/8/F/9/8F93DBBD-896B-4760-AC81-646F61363A6D/WcfDataServices.exe", # Microsoft WCF Data Services 5.0
        "http://download.microsoft.com/download/9/1/D/91DA8796-BE1D-46AF-8489-663AB7811517/setup_msipc_x64.msi", # Microsoft Information Protection and Control Client (MSIPC)
        "http://download.microsoft.com/download/E/0/0/E0060D8F-2354-4871-9596-DC78538799CC/Synchronization.msi", # Microsoft Sync Framework Runtime v1.0 SP1 (x64)
        "http://download.microsoft.com/download/0/1/D/01D06854-CA0C-46F1-ADBA-EBF86010DCC6/r2/MicrosoftIdentityExtensions-64.msi", # Windows Identity Extensions
        "http://download.microsoft.com/download/D/7/2/D72FD747-69B6-40B7-875B-C2B40A6B2BDD/Windows6.1-KB974405-x64.msu", # Windows Identity Foundation (KB974405)
        "http://download.microsoft.com/download/A/6/7/A678AB47-496B-4907-B3D4-0A2D280A13C0/WindowsServerAppFabricSetup_x64.exe", #Windows Server AppFabric
        "http://download.microsoft.com/download/7/B/5/7B51D8D1-20FD-4BF0-87C7-4714F5A1C313/AppFabric1.1-RTM-KB2671763-x64-ENU.exe" # CU 1 for AppFabric 1.1 (KB2671763)
             )

function CreateDestinationFolder()
{
    Try
    {
        ## Return true if the Destination Folder exists, otherwise return false
        If (!(Test-Path "$DestinationFolder" -pathType container))
        {
            ##Creates the destination folder if it does not exist
            New-Item $DestinationFolder -ItemType Directory
        }
    }
    Catch
    {
        Write-Host "An error occurred creating destination folder (`'$DestinationFolder`'), Please check the path,and try again."
        Pause
        break
    }
}

function DownloadSP2013Files()
{
    Import-Module BitsTransfer
    Write-Host "BitsTransfer Module is loaded"
    Write-Host "Downloading..."

    ForEach ($FileUrl in $FilesUrlList)
    {
        ## Get the file name
        $DestinationFileName = $FileUrl.Split('/')[-1]
   
        Try
        {
           
            ## Return true if the file exists, otherwise return false
            If (!(Test-Path "$DestinationFolder\$DestinationFileName"))
            {
                Write-Host "`'$FileUrl`' ..."
                Start-BitsTransfer -Source $FileUrl -Destination $DestinationFolder\$DestinationFileName -Priority High -ErrorVariable err
                If ($err) {Throw ""}
            }
            Else
            {
                Write-Host "File $DestinationFileName already exists, skipping..."
            }
        }
        Catch
        {
            Write-Warning "An error occurred downloading `'$DestinationFileName`'"
            break
        }
    }
}

function Pause($Message="Press any key to continue...")
{
    Write-Host -NoNewLine $Message
    $null = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    Write-Host ""
}

CreateDestinationFolder
DownloadSP2013Files
Pause

Download Picture from UPS SharePoint Server

[system.reflection.assembly]::LoadWithPartialName("System.IO")
[system.reflection.assembly]::LoadWithPartialName("System.Web")


$SUrl = 'http://servername:8888/_vti_bin/userprofileservice.asmx?wsdl'
$filename = 'D:\UPSPictures\report01.csv'

$stream = [System.IO.StreamWriter] "D:\UPSPictures\reportsAll.csv"

function Download()
{
    trap [Exception]
        {
            Write-Output "-------------------------------Error"    
            Write-Output $_.Exception.Message
            Write-Output "-------------------------------Error"
            continue
        }

        $datel = Get-Date
        Write-Output "INFO: `t $datel `t Job Started"

        Write-Host "Set Path to Store Pictures" 
        $FilePath = "D:\UPSPictures"

        if($FilePath.EndsWith("\") -eq $false)
        {
          $FilePath = $FilePath + "\"
        }

        Write-Host "Enter the User Profile Web Service Url"
        #$SUrl = Read-Host

        Write-Host "Enter the User name & Password using which it needs to connect the service"
        #Create Credential Object
        $Credential = Get-Credential

        #Get Service
        #$Service = New-WebServiceProxy -Uri $SUrl -NameSpace UserProfileService -UseDefaultCredential
        $Service = New-WebServiceProxy -Uri $SUrl -NameSpace UserProfileService -Credential $Credential


        #Create WebRequest
        $WebRequest = new-object System.Net.WebClient
        #$WebRequest.Credentials = [System.Net.CredentialCache]::DefaultCredentials
        #$WebRequest.Credentials = new-object System.Net.NetworkCredential("palnisam","password","domain")
        $WebRequest.Credentials =  $Credential.GetNetworkCredential()


        #[IO.Directory]::SetCurrentDirectory((Convert-Path (Get-Location -PSProvider FileSystem)))
        #$Reader = new-object System.IO.StreamReader($filename)

        $ProfileCount = $Service.GetUserProfileCount()
        $ProfileLoop  = 0;
        $NextIndex = 358;
        for($ProfileLoop = 0;$ProfileLoop -le $ProfileCount;$ProfileLoop++)
        {
            trap [Exception]
            {
            }

            $UPD = $Service.GetUserProfileByIndex($NextIndex)
           
            #$AccountName = $UPD.UserProfile[1].Values[0].Value
           
            $Prop = $UPD.UserProfile | Where-Object { $_.Name -eq "AccountName" }
            $AccountName = $Prop.Values[0].Value

            #$PictureURL = $UPD.UserProfile[20].Values[0].Value
           
            $Prop = $UPD.UserProfile | Where-Object { $_.Name -eq "PictureURL" }
            $PictureURL = $Prop.Values[0].Value

            #if($PictureURL -ne $null)
            #{
              #$FileName = $FilePath +$AccountName.SubString($AccountName.LastIndexOf("\")+1) + $PictureUrl.SubString($PictureUrl.LastIndexOf("."))
              #$WebRequest.DownloadFile($PictureUrl,$FileName)
              $stream.WriteLine( "$AccountName ; $PictureURL" )
              #Write-Host "$ProfileLoop ; $AccountName ; $FILENAME; $PictureURL"
            #}

            $NextIndex = $UPD.NextValue

        }
    $stream.close()
}

Download