SharePoint.2013.Toolbox.psm1

function Set-SP2013SuiteBarText{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true,Position=1)] [string]$WebApp,
        [Parameter(Mandatory = $true,Position=2)] [string]$Text,
        [Parameter(Mandatory = $false,Position=3)] [string]$Link = $null
    )
    Try {
        $ver = $host | Select-Object version
        if ($ver.Version.Major -gt 1) {$host.Runspace.ThreadOptions = "ReuseThread"} 
        if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction Stop) -eq $null) {
            Write-Verbose "Adding SharePoint PowerShell Snapin"
            Add-PSSnapin "Microsoft.SharePoint.PowerShell"
        }
    }
    Catch [System.Exception]{
        Write-Warning "SharePoint PowerShell Snapin is not found"
    }
    
    $spWebapp = Get-SPWebApplication -Identity $WebApp 
    if ($Link -ne $null)
    {
        $spWebapp.SuiteBarBrandingElementHtml = '<div class="ms-core-brandingText" style="font-size: 15px !important; padding-left: 10px;"><a href="'+$Link+'" class="ms-core-suiteLink-a"><span>'+$Text+'</span></a></div>'
    }
    else
    {
        $webspWebappApp.SuiteBarBrandingElementHtml = '<div class="ms-core-brandingText">'+$Text+'</div>'
    }    
    $spWebapp.Update()
}

function Set-SP2013SiteLogo{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$True,Position=1)] [string]$SiteURL,
        [Parameter(Mandatory=$False,Position=2)] [string]$SiteLogoUrl = "",
        [Parameter(Mandatory=$False,Position=3)] [string]$SiteLogoDescription = ""
    )
    Try {
        $ver = $host | Select-Object version
        if ($ver.Version.Major -gt 1) {$host.Runspace.ThreadOptions = "ReuseThread"} 
        if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction Stop) -eq $null) {
            Write-Verbose "Adding SharePoint PowerShell Snapin"
            Add-PSSnapin "Microsoft.SharePoint.PowerShell"
        }
    }
    Catch [System.Exception]{
        Write-Warning "SharePoint PowerShell Snapin is not found"
    }
    
    $SPSite = Get-SPSite $SiteURL
    $SPSite.AllWebs | ForEach-Object { $_.SiteLogoUrl = $SiteLogoUrl; $_.SiteLogoDescription = $SiteLogoDescription; $_.Update() }
}

function Set-SP2013PoralLink{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$True,Position=1)] [string]$SiteURL,
        [Parameter(Mandatory=$True,Position=2)] [string]$PortalUrl,
        [Parameter(Mandatory=$True,Position=3)] [string]$PortalName
    )
    Try {
        $ver = $host | Select-Object version
        if ($ver.Version.Major -gt 1) {$host.Runspace.ThreadOptions = "ReuseThread"} 
        if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction Stop) -eq $null) {
            Write-Verbose "Adding SharePoint PowerShell Snapin"
            Add-PSSnapin "Microsoft.SharePoint.PowerShell"
        }
    }
    Catch [System.Exception]{
        Write-Warning "SharePoint PowerShell Snapin is not found"
    }
    
    $SPSite = Get-SPSite $SiteURL
    $SPSite.PortalName = $PortalName 
    $SPSite.PortalUrl = $PortalUrl
}

function Start-SP2013Farm{
    $Host.Runspace.ThreadOptions = "ReuseThread"
    Start-SPAssignment -Global
    $SPWebApps = Get-SPWebApplication -IncludeCentralAdministration
    foreach ($SPWebApp in $SPWebApps){
        foreach ($SPSite in $SPWebApp.Sites) { 
            foreach ($spWeb in $SPSite.AllWebs) {
                Write-Host -NoNewline "Warming up "$spWeb.url
                Try{
                    $r = Invoke-WebRequest -URI $spWeb.url -UseDefaultCredentials
                    if ($r.StatusCode -ne 200) { throw [System.IO.FileNotFoundException] $spWeb.Url + "Status Code is" + $r.StatusCode }
                    Write-Host -ForegroundColor Green " .....Done!"
                } Catch {
                    Write-Host -ForegroundColor Red " .....Error!"
                }
            }
        }
    }
    Stop-SPAssignment -Global
}

function Set-SP2013MaintenanceMode {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$false)][switch]$Online
    )
    Function Set-OfflinePage() {
        Param(
            [Parameter(Position=0, Mandatory=$true)][string]$Location
        )
        $file = $Location+"\app_offline.htm"
        Out-File -FilePath "\app_offline.htm"
        $html = "<html><head><title>SharePoint is currently offline</title></head>"
        $html += "<body><h1 style='text-align:center'>SharePoint is currently undergoing maintenance</h1></body>"
        $html += "</html>"
        Add-Content -Path $file -Value $html
    }

    Start-SPAssignment -Global
    $spWebApplications = Get-SPWebApplication
    if ($Online) {
        foreach ($spWebApplication in $spWebApplications){
            try {
                Write-Host -NoNewline "Putting"$spWebApplication.url"back online"
                $IISSettings = $spWebApplication.IisSettings[[Microsoft.SharePoint.Administration.SPUrlZone]::Default]
                $file = $IISSettings.Path.FullName+"\app_offline.htm"
                Remove-Item $file
                Write-Host -ForegroundColor Green ".....Done!"
            }
            catch {
                Write-Host -ForegroundColor Red ".....Error!"
            }
        }
        Start-SP2013Farm
    }
    else {
        foreach ($spWebApplication in $spWebApplications){
            try {
                Write-Host -NoNewline "Taking"$spWebApplication.url"offline"
                $IISSettings = $spWebApplication.IisSettings[[Microsoft.SharePoint.Administration.SPUrlZone]::Default]
                Set-OfflinePage $IISSettings.Path.FullName
                Write-Host -ForegroundColor Green " .....Done!"
            }
            catch {
                Write-Host -ForegroundColor Red ".....Error!"
            }
        }
    }
    Stop-SPAssignment -Global
}

function Backup-SP2013Farm{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$True,Position=1)]
        [string]$Path,
        [Parameter(Mandatory=$True,Position=2)]
        [int]$RetentionDays
    )
    Function Backup-SPSiteCollection {
        Param(
            [Parameter(Position=0, Mandatory=$true)][string]$Location,
            [Parameter(Position=0, Mandatory=$true)][string]$URL,
            [Parameter(Position=0, Mandatory=$true)][string]$SiteTitle
        )
        Try {
            Write-Host -NoNewline "Backing up Site Collection $SiteTitle"
            Backup-SPSite $URL -Path $Location
            Write-Host -ForegroundColor Green ".....Done!"
            Write-Host -ForegroundColor Yellow "Backup file located at $Location"
        }
        Catch {

        }
    }
    Start-SPAssignment -Global
    $SPWebApps = Get-SPWebApplication
    $BackupRetentionDate = (Get-Date).AddDays(-$RetentionDays)
    $currentDate = Get-Date
    $bkDate = $currentDate.Year.ToString("0000") + $currentDate.Month.ToString("00") + $currentDate.Day.ToString("00")
    foreach ($SPWebApp in $SPWebApps){
        Write-Host -ForegroundColor Yellow "Starting Backup of Site Collections in "$SPWebApp.URL
        $spWebAppBackupFolder = $SPWebApp.URL.Replace("http://","").Replace("https://","").Replace(".","-").Replace("/","\")
        $bkLocation = $Path + '\' + $spWebAppBackupFolder
        if(!(Test-Path -Path $bkLocation )){ New-Item -ItemType directory -Path $bkLocation | Out-Null }
        Get-ChildItem -Path $bkLocation -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $BackupRetentionDate } | Remove-Item -Force
        foreach ($SPSite in $SPWebApp.Sites) { 
        if ($SPSite.ServerRelativeUrl -eq "/") { $bkFileName = $bkDate + "-root.bak" }
        else { $bkFileName = $bkDate + $SPSite.ServerRelativeUrl.Replace(".","-").Replace("/","-").Replace(" ","-") + ".bak" }
        $bkFile = $bkLocation + $bkFileName
        Backup-SPSiteCollection -Location $bkFile -URL $SPSite.URL -SiteTitle $SPSite.RootWeb.Title
        $SPSite.Dispose()        
        }
        Write-Host "Backup of Site Collections in "$SPWebApp.URL" Completed"
    }
}

function Get-SP2013Permissions{
    [CmdletBinding()]
    param(
        [Parameter(Position=1,Mandatory=$true)][string]$Site,
        [Parameter(Position=2,Mandatory=$true)][string]$Output
    )
    Try {
        $ver = $host | Select-Object version
        if ($ver.Version.Major -gt 1) {$host.Runspace.ThreadOptions = "ReuseThread"} 
        if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction Stop) -eq $null) {
            Write-Verbose "Adding SharePoint PowerShell Snapin"
            Add-PSSnapin "Microsoft.SharePoint.PowerShell"
        }
    }
    Catch [System.Exception]{
        Write-Warning "SharePoint PowerShell Snapin is not found"
    }

    $results = @()
    $spSite = Get-SPSite $Site
    Try{
        Write-Host -NoNewline "Getting Site Collections Administrators for"$spSite.URL
        if ($spSite.Owner -ne $null)
        {
            $details = @{
                SiteName    = $spWeb.Title
                SiteURL     = $spWeb.URL
                Group       = "Site Owner"      
                Role        = "Site Collection Administrator"
                User        = $spSite.Owner.DisplayName             
                UserName    = $spSite.Owner.UserLogin.Replace("i:0#.w|","")
                Inherited   = $false
            }                           
            New-Object PSObject -Property $details  | export-csv -Path $Output -NoTypeInformation -Append  
        }
        if ($spSite.SecondaryContact -ne $null)
        {
            $details = @{
                SiteName    = $spWeb.Title
                SiteURL     = $spWeb.URL
                Group       = "Site Owner"
                Role        = "Site Collection Administrator"      
                User        = $spSite.SecondaryContact.DisplayName             
                UserName    = $spSite.SecondaryContact.UserLogin.Replace("i:0#.w|","")
                Inherited   = $false
            }                           
            New-Object PSObject -Property $details  | export-csv -Path $Output -NoTypeInformation -Append  
        }
        Write-Host -f Green " .....Dome!"
    }
    Catch
    {
        Write-Host -f Red " .....Error!"
    }

    foreach ($spWeb in $spSite.AllWebs)
    {
        Write-Host -NoNewline "Getting Users and Permissions for"$spWeb.URL
        if ($spWeb.IsRootWeb)
        {
            foreach ($spSiteAdmin in $spWeb.SiteAdministrators)
            {
                if ($spSiteAdmin.UserLogin -ne $spSite.Owner.UserLogin -and 
                    $spSiteAdmin.UserLogin -ne $spSite.SecondaryContact.UserLogin)
                {
                    $details = @{
                        SiteName    = $spWeb.Title
                        SiteURL     = $spWeb.URL
                        Group       = "Administrator"        
                        Role        = "Site Collection Administrator"
                        User        = $spSiteAdmin.name              
                        UserName    = $spSiteAdmin.UserLogin.Replace("i:0#.w|","")
                        Inherited   = $spWeb.Permissions.Inherited
                    }                           
                    New-Object PSObject -Property $details  | export-csv -Path $Output -NoTypeInformation -Append  
                }
            } 
        }
        foreach ($spGroup in $spWeb.sitegroups)
        {
            foreach ($spUser in $spGroup.users)
            {
                if ($spGroup.Roles.Count -eq 1)
                {
                    $details = @{
                        SiteName    = $spWeb.Title
                        SiteURL     = $spWeb.URL
                        Group       = $spGroup.name      
                        Role        = $spGroup.Roles.Name      
                        User        = $spUser.name              
                        UserName    = $spUser.UserLogin.Replace("i:0#.w|","")
                        Inherited   = $spWeb.Permissions.Inherited
                    }                           
                    New-Object PSObject -Property $details  | export-csv -Path $Output -NoTypeInformation -Append  
                }
                elseif ($spGroup.Roles.Count -gt 1)
                {
                    foreach ($spRole in $spGroup.Roles)
                    {
                        if ($spRole.Name -ne "Limited Access"){
                            $details = @{
                                SiteName    = $spWeb.Title
                                SiteURL     = $spWeb.URL
                                Group       = $spGroup.name      
                                Role        = $spRole      
                                User        = $spUser.name              
                                UserName    = $spUser.UserLogin.Replace("i:0#.w|","")
                                Inherited   = $spWeb.Permissions.Inherited
                            }                           
                            New-Object PSObject -Property $details  | export-csv -Path $Output -NoTypeInformation -Append
                        }  
                    }
                }
            }
        }
        foreach ($spRole in $spWeb.Roles)
        {
            if ($spRole.Users -ne $null -and $spRole.Type -ne "Administrator")
            {
                foreach ($spUser in $spRole.Users)
                {
                    $details = @{
                        SiteName    = $spWeb.Title
                        SiteURL     = $spWeb.URL
                        Group       = "Given Explicitly"
                        Role        = $spRole.Type      
                        User        = $spUser.DisplayName             
                        UserName    = $spUser.UserLogin
                        Inherited   = $spWeb.Permissions.Inherited
                    }                           
                    New-Object PSObject -Property $details  | export-csv -Path $Output -NoTypeInformation -Append 
                }
            }
        }
        Write-Host -f Green " .....Done!"
    }

    $spSite.dispose()
}

Export-ModuleMember -Function *