How To: Compare two text files with PowerShell

Intro

This post shows the code to compare two text files and determine whether the content is identical or not, as well as listing a line by line comparison. This utility could be useful to verify some scenarios, such as migrations, upgrades.

Comparing two files with PowerShell

The script below takes two files stored in the Desktop, compares their content, and prints a message to determine whether they are identical or not.

$desktopFolder = [Environment]::GetFolderPath("Desktop")
$fileA = "$desktopFolder\FileA.txt"
$fileB = "$desktopFolder\FileB.txt"

If (Compare-Object -ReferenceObject $(Get-Content $fileA) -DifferenceObject $(Get-Content $fileB))
{
  Write-Host "Different" -foregroundcolor red
}
Else
{
  Write-Host "Identical" -foregroundcolor green
}

The second script compares two files and provides a line by line comparison.

$desktopFolder = [Environment]::GetFolderPath("Desktop")
$fileA = "$desktopFolder\FileA.txt"
$fileB = "$desktopFolder\FileB.txt"

Compare-Object $(Get-Content $fileA) $(Get-Content $fileB) -includeequal

Reference

Using the Compare-Object Cmdlet – TechNet

How to enable the Developer Dashboard in SharePoint 2013

Intro

The SharePoint Developer Dashboard is a built-in tool that has been available since SharePoint 2010. It provides diagnostic information that can be used by developers and system administrators to identify and troubleshoot issues related to page components. It also makes it easier to identify performance issues and resource usage right from the current page, which is easier than analyzing raw data from the ULS logs.

This post provides some details about changes to the developer dashboard in SharePoint 2013 and a PowerShell script to enable and disable the dashboard.

Changes to Developer DashBoard in SharePoint 2013

  • In SP 2010, the Developer Dashboard was rendered as a control in the master page, and it only showed information about the current request. In SP 2013 it shows as a separate window and it shows information about all request since the dashboard was enabled
  • The dashboard depends on “Usage and Health Data Collection Service Application”. This service must have been created and it must be running, otherwise no data trace data will be displayed (see Wictor Wilén post below).
  • The dashboard can be enabled (On) and disabled (Off). See the PowerShell below for performing these two actions.
  • The following tags must be present in the master page:
<SharePoint:DeveloperDashboard runat="server" />
<SharePoint:DeveloperDashboardLauncher
    ID="DeveloperDashboardLauncher"
    ThemeKey="spcommon"
    TouchMode="true"
    TouchModeWidth="30"
    TouchModeHeight="30"
    TouchModePaddingLeft="7"
    TouchModePaddingTop="7"
    TouchModePaddingRight="7"
    TouchModePaddingBottom="7"
    NavigateUrl="#"
    OnClick="ToggleDeveloperDashboard();return false"
    OuterCssClass="ms-dd-button ms-qatbutton"
    runat="server"
    ImageUrl="/_layouts/15/images/spcommon.png"
    AlternateText="<%$Resources:wss,multipages_launchdevdashalt_text%>"
    ToolTip="<%$Resources:wss,multipages_launchdevdashalt_text%>"
    OffsetX="237"
    OffsetY="30"
    HoverOffsetX="219"
    HoverOffsetY="66"
    Height="16"
    Width="16" />

PowerShell Script

The following script can be used to enable or disable the developer dashboard in a SharePoint 2013 farm:

# Add SharePoint cmdlets reference 
Add-PSSnapin "Microsoft.SharePoint.Powershell" -ErrorAction SilentlyContinue

#Enable Dashboard
$contentSvc = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
$devDahsboardSettings = $contentSvc.DeveloperDashboardSettings
$devDahsboardSettings.DisplayLevel = "On"
$devDahsboardSettings.Update()

#Disable Dashboard
$contentSvc = ([Microsoft.SharePoint.Administration.SPWebService]::ContentService)
$devDahsboardSettings =$contentSvc.DeveloperDashboardSettings
$devDahsboardSettings.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::Off
$devDahsboardSettings.Update()

Summary

The SharePoint developer dashboard is a great tool to identify and troubleshoot page issues. In addition to ULSViewer, the dashboard is a great addition to the developer toolset for assisting in fine tuning custom components and ensuring good performance.

Reference

Using the Developer DashBoard (MSDN)

Developer Dashboard in SharePoint 2013

SharePoint 2013: Developer Dashboard shows no data “issue” (Wictor Wilén)

 

Testing content database before migrating to SharePoint 2013

Introduction

One of the steps in the SharePoint 2013 migration process is to test the content databases to identify potential issues before migrating to the new 2013 schema. This article shows a PowerShell script to execute the validation and export the results to a CSV file. Special kudos to Joe Rodgers for the original algorithm. I modified the code a little bit to be able to pass the parameters and focus on one DB at the time.

Script

Param(
 [Parameter(Mandatory=$true)] [string]$DBName,
 [Parameter(Mandatory=$true)] [string]$WebAppUrl
)

# array to store the output
$results = @()

Test-SPContentDatabase -Name $DBName -WebApplication $WebAppUrl | % {
   # get the SPContentDatabaseTestResultObject
   $databaseTestResult = $_

   # create a hash table
   $props = @{}

   # add the database name to the output
   $props.Add("DatabaseName", $DBName) 

   # dynamically add all of the SPContentDatabaseTestResult properties to the output
   $_ | Get-Member -MemberType *Property | % { 
     $props.Add($_.Name, $databaseTestResult.($_.Name)) 
   } 

   # add the hashtable to the output array
   $results += New-Object PSObject -Property $props
}

# dump the output to csv
$results | Export-Csv $("Test-ContentDatabaseResults_{1}_{0}.csv" -f (Get-Date).ToString("yyyy-MM-dd_hhmmss"), $DBName) -NoTypeInformation

How to use the Script

  1. Copy the above code into a file a name it “TestDB.ps1
  2. Save the file to a local directory in the SharePOint Server i.e: “c:\temp”
  3. Open SharePoint Management Shell
  4. Navigate to the script location i.e: “PS> cd c:\temp”
  5. Execute the script with the two parameters. i.e: PS> TestDB.ps1 -DBName <NameOfDatabase> -WebAppUrl <UrlOfWebApp>
  6. On successful completion, a CSV file is generated containing the DB name and the time stamp in the title i.e: Test-ContentDatabaseResults_DBName_2016-07-05_025815.csv
  7. Repeat the steps for each content DB to be upgraded

Reference

Upgrade Content Databases to SharePoint 2013

Export Test-SPContentDatabase Results to a CSV File

 

Setup SharePoint 2013 Single Server Environment – Part 4: SQL Server setup

Intro

This series describes the details and required steps for setting up a SharePoint 2013 Single Server Environment. This is typically used by developers in order to write custom solutions without interfering with one another. This type of environment is also is good for evaluation, training and demonstration purposes.
The series contains 6 parts:
  1. Environment Details
  2. VM setup
  3. Windows Server 2012 setup
  4. SQL Server setup
  5. SharePoint Installation and Initial Configuration
  6. Post-Installation Steps

SQL Server setup

This article contains the required steps to properly setup the SQL Server environment to properly run a single server SharePoint 2013 environment.

Install SQL Server 2012 Features

As per the previous article in this series, we should have downloaded the SQL Server 2012 ISO installation file and added it to the VM as a Virtual Optical Drive by now.
  1. From the virtual drive containing SQL installation, Run SETUP.EXE
  2. Select at least the following Core Features:
    1. Database Engine Services
    2. Management Tools – Basic
    3. Management Tools – Complete
  3. Select additional features based on specific needs

Setup Max Degrees of parallelism

Update the following PowerShell script, specifying the appropriate server instance.

#### Set MDOP to 1
Import-Module "sqlps" -DisableNameChecking
$sql = "EXEC sys.sp_configure N'show advanced options', N'1' RECONFIGURE WITH OVERRIDE
GO
EXEC sys.sp_configure N'max degree of parallelism', N'1'
GO
RECONFIGURE WITH OVERRIDE
GO
EXEC sys.sp_configure N'show advanced options', N'0' RECONFIGURE WITH OVERRIDE
GO"
Invoke-Sqlcmd -Query $sql [-ServerInstance "SERVER\instance"]

Open a PowerShell console with administrator credentials and execute the above script.

Note: If you are unable to execute PowerShell commands on the server, you may need to change the execution policy. See this link for reference. 

Delegate Permissions

  1. Open SQL Management Studio
  2. Create SQL Login for sp_admin service account
  3. Assign server roles:
    1. dbcreator
    2. securityadmin

 

<< Windows Server 2012 Setup SharePoint Installation & Config..>>

 Reference

Using the Set-ExecutionPolicy Cmdlet in PowerShell

 

How to get the bytes from a file and convert them to Base64String in PowerShell

Introduction

In this post I’ll share a PowerShell script, that simply reads the bytes from a given file, converts those bytes to a Base64String, and then saves it to a text file.

A little background about why I needed this

I needed to troubleshoot a web service method and I wanted to use SOAP UI as the testing framework. The service method took a byte[] as a parameter and uploaded the corresponding file to a Yammer network.

I’ve been using SOAP UI for testing web services, but most of the times the requests were taking simple types, such as integers and strings. I learned that the way to pass a byte[] to an ASP.NET web service method is to use the Base64String representation, so my next task was to get the Base64String representation of any given file, so I could grab it as simple text and pass it to the XML test request. Rather than creating a console application, I thought that a PowerShell script would get it done faster.

Here is the script

#Get the bytes of a given file
$fileBytes = Get-Content <fileNameAndPath> -Encoding byte

#Convert byte array to base64 string
$fileBytesBase64 = [Convert]::ToBase64String($filebytes)

#Save Base64String to a text file
Add-Content outputFileBytesBase64.txt $fileBytesBase64

Reference

I was able to gather useful tips from these posts:

PowerShell Encoding and Decoding (Base64) – by Sean Metcalf

Efficient Base64 conversion in PowerShell – by mnaoumov