BLOG

IT Pro fear no more! Introducing the SPCAF PowerShell CmdLet

7 min read
Blog Header Developer

Attention IT Pros!

This time we have something for you!

PowerShellWe are happy to announce the availability of the new SPCAF PowerShell CmdLet enabling you to analyze the code quality of your SharePoint solutions (.wsp) and apps (.apps) in your solution deployment scripts, your farm health checks or anywhere else you are using PowerShell to automate SharePoint management tasks including migration and governance solutions like AvePoint’s DocAve, Metalogix Content Matrix or Sharegate’s Sharegate 🙂

SPCAF PowerShell includes the same five analysis components as the the full client for Code Quality Analysis, Metrics, Dependency Analysis, Inventory and Migration Assessment.

With the PowerShell provided scripts you can download all WSP solutions and apps and check them against over 600 code quality rules. The generated reports show you if the solutions are well developed or contain issues which may harm the performance, supportability and stability of your farm.

Get a free Code Quality Summary Report

If you don’t own a license SPCAF creates a free summary report (HTML) that highlights the found issues and their categories and summarizes the code metrics.

SummaryReport
SPCAF Summary Report

Integrate the Analysis into your Solution Deployment Process

SPSDIf you already use PowerShell to deploy solutions and apps to SharePoint, for example with the help of our free SharePoint Solution Deployer (SPSD) script, then you can easily integrate the SPCAF analysis into your deployment process:

Run the analysis right before the customizations are deployed to SharePoint and stop the deployment if critical issues have been identified. This ensures a better code quality of your deployed solutions and apps and improves stability, performance and security of your SharePoint environment.

How to use SPCAF PowerShell

Using SPCAF PowerShell is very straight forward. After importing the SPCAF.PowerShell.dll module you can invoke an analysis for a single solution or app or for a complete folder.
You can pass your custom ruleset configuration to adjust which rules are checked as well as define the output formats and the report location and name.

Example:

Import-Module "SPCAF.PowerShell.dll" 

Invoke-SPCAFCodeAnalysis -InputFiles "d:\FolderWithWSPs" -Reports "HTML;PDF" -OutputFile "d:\SPCAFOutput\SPCAF-Report.html"

To make your life easier the download already includes two sample scripts to show you how to

1. AnalyzeSolutionsLocally.ps1

<#
.SYNOPSIS
    SPCAF SharePoint Code Analysis
	This powershell file analyzes a given set of SharePoint .wsp and .app files and 
	detects critical errors and warnings in the contained code.
.DESCRIPTION    
	All parameters can be configured in the script for ease of use, see more in the configuration section below.
	The product is available under a limited free licence.
	To view a comparison of the features in each version please see this URL
	http://www.spcaf.com/purchase/feature-comparison/
.LINK
	SPCAF Documentation
	http://docs.spcaf.com
.NOTES
    Author: RENCORE AB
    Date:   November 20, 2014    
#>

##################################################################################
# Configurable values
##################################################################################

# Path to directory with .wsp files or a comma-separated list of .wsp files for the analysis
$InputFiles = "D:\FolderWithWSPs";

# Path to output folder for the reports
$OutputDirectory = "D:\SPCAFOutput";

# ReportName - The name of the report to be output
$ReportName = "SPCAFReport";

# TimeStampReportFilename - Whether the date and time should be appended to the report file
# $TRUE or $FALSE
$TimeStampReportFilename = $TRUE;

# Reports - Formats required: HTML,DOCX,PDF,XML,CSV
$Reports = @("HTML","PDF");

# LogFile - The name of the analysis log file, this will be output to the DLL directory
$LogFileName = "SPCAFLog";

# TimeStampLogfileFilename - Whether the date and time should be appended to the log file
# $TRUE or $FALSE
$TimeStampLogfileFilename = $TRUE;

# LicenceFiles Licence path(s) - Comma seperated list of paths, you may need to
# Optional remark out to not use a licence
$LicenseFiles = @();
#$LicenseFiles = @("f:\spcaf\server.lic");
#$LicenseFiles = @("f:\spcaf\server.lic","f:\spcaf\inventory.lic");

# Timeout - Value in seconds, remark out or 0 for no timeout
$Timeout = 20000;

# Verbose - Verbose mode $TRUE or $FALSE
$Verbose = $TRUE;

##################################################################################
# IMPORTAMT: It is recommended that only advanced users edit below this line
##################################################################################

# Other things you might want to do:
# - Load in CSV reports, and produce an comparison over time
# - Auto email reports on schedule

########################################################
# Execute SPCAF Code Analysis on WSPs
########################################################
$ScriptDir = Split-Path -parent $MyInvocation.MyCommand.Path
Import-Module "$ScriptDir\SPCAF.PowerShell.dll"

$params = @{
	InputFiles = @()
	OutputFile = ""
	Reports = @("HTML")
	LicenseFiles = @()
	Timeout = 0
	LogFile = ""
};
if($InputFiles -ne $null)
{
	$params.InputFiles = $InputFiles;
}
if($ReportName -ne $null)
{
	$DateTimeStamp = "";
	if($TimeStampReportFilename)
	{
		$DateTimeStamp = $(get-date -f "yyyyMMdd-HHmmss");
	}	
	$params.OutputFile = "$OutputDirectory\$ReportName$TimeStamp.rep";
}
if($LogFileName -ne $null)
{
	$DateTimeStamp = "";
	if($TimeStampLogfileFilename)
	{
		$DateTimeStamp = $(get-date -f "yyyyMMdd-HHmmss");
	}	
	$params.LogFile = "$OutputDirectory\$LogFileName$TimeStamp.log";
}
if($Reports -ne $null)
{
	$params.Reports = $Reports;
}
# If we are using free version we remove this param
if($LicenseFiles -ne $null)
{
	$params.LicenseFiles = $LicenseFiles;
}
else
{
	$params.LicenseFiles = $null;
}
if($Timeout -ne $null)
{
	$params.Timeout = $Timeout;
}
Invoke-SPCAFCodeAnalysis @params -Verbose:$Verbose;

 2. LoadAndAnalyzeSolutionsFromSharePoint.ps1

<#
.SYNOPSIS
    SPCAF SharePoint Code Analysis
	This powershell file connects to a local SharePoint Farm, downloads the full trust solutions,
	then scans each wsp.
.DESCRIPTION    
	All parameters can be configured in the script for ease of use, see more in the configuration section below.
	The product is available under a limited free licence.
	To view a comparison of the features in each version please see this URL
	http://www.spcaf.com/purchase/feature-comparison/
.LINK
	SPCAF Documentation
	http://docs.spcaf.com
.NOTES
    Author: RENCORE AB
    Date:   November 20, 2014    
#>

##################################################################################
# Configurable values
##################################################################################

# Path to output folder for the reports
$OutputDirectory = "D:\SPCAFOutput";

# ReportName - The name of the report to be output
$ReportName = "SPCAFReport";

# TimeStampReportFilename - Whether the date and time should be appended to the report file
# $TRUE or $FALSE
$TimeStampReportFilename = $TRUE;

# Reports - Formats required: HTML,DOCX,PDF,XML,CSV
$Reports = @("HTML","PDF");

# LogFile - The name of the analysis log file, this will be output to the DLL directory
$LogFileName = "SPCAFLog";

# TimeStampLogfileFilename - Whether the date and time should be appended to the log file
# $TRUE or $FALSE
$TimeStampLogfileFilename = $TRUE;

# LicenceFiles Licence path(s) - Comma seperated list of additional paths
$LicenseFiles = @();
#$LicenseFiles = @("f:\spcaf\server.lic");

# Timeout - Value in seconds, remark out or 0 for no timeout
$Timeout = 20000;

# Verbose - Verbose mode $TRUE or $FALSE
$Verbose = $TRUE;

##################################################################################
# IMPORTAMT: It is recommended that only advanced users edit below this line
##################################################################################

# Other things you might want to do:
# - Include more solution types (Example download scripts here: https://rencore.com/blog/sharepoint-health-check-2-extracting-customizations/ )
# - Remote powershell download of Farm Solutions
# - Load in CSV reports, and produce an comparison over time
# - Auto email reports on schedule

##############################################################
# Create a temporary folder to save the downloaded wsp files #
##############################################################

$TempFolder = [system.guid]::newguid().tostring()
$InputFiles = "$env:temp\$TempFolder"
New-Item -Force -ItemType directory -Path $InputFiles

########################################################
# Download all Full-Trust solutions from the local farm
########################################################
$ver = $host | select version
if ($ver.Version.Major -gt 1) {$host.Runspace.ThreadOptions = "ReuseThread"} 
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) 
{
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
(Get-SPFarm).Solutions | % {
	$_.SolutionFile.SaveAs($InputFiles + "\" + $_.Name)
	Write-Host $InputFiles + "\" + $_.Name + " downloaded"
}

########################################################
# Execute SPCAF Code Analysis on downloaded WSPs
########################################################
$ScriptDir = Split-Path -parent $MyInvocation.MyCommand.Path
Import-Module "$ScriptDir\SPCAF.PowerShell.dll"

$params = @{
	InputFiles = @()
	OutputFile = ""
	Reports = @("HTML")
	LicenseFiles = @()
	Timeout = 0
	LogFile = ""
};
if($InputFiles -ne $null)
{
	$params.InputFiles = $InputFiles;
}
if($ReportName -ne $null)
{
	$DateTimeStamp = "";
	if($TimeStampReportFilename)
	{
		$DateTimeStamp = $(get-date -f "yyyyMMdd-HHmmss");
	}	
	$params.OutputFile = "$OutputDirectory\$ReportName$TimeStamp.rep";
}
if($LogFileName -ne $null)
{
	$DateTimeStamp = "";
	if($TimeStampLogfileFilename)
	{
		$DateTimeStamp = $(get-date -f "yyyyMMdd-HHmmss");
	}	
	$params.LogFile = "$OutputDirectory\$LogFileName$TimeStamp.log";
}
if($Reports -ne $null)
{
	$params.Reports = $Reports;
}
# If we are using free version we remove this param
if($LicenseFiles -ne $null)
{
	$params.LicenseFiles = $LicenseFiles;
}
else
{
	$params.LicenseFiles = $null;
}
if($Timeout -ne $null)
{
	$params.Timeout = $Timeout;
}
Invoke-SPCAFCodeAnalysis @params -Verbose:$Verbose;

##########################################################
# Finally delete the temp directory with downloaded wsps #
##########################################################

Remove-Item -Recurse -Force $InputFiles

If you like to download additionally apps and sandboxed solutions from your farm for the analysis, then check out my blog on how to extract all customizations from your farm in which you will find the required PowerShell script.

Command Line Parameters

SPCAF PowerShell comes with a range of parameters that allow you to configure the analysis to your needs.

Parameter Value Mandatory Description
InputFiles String Array Yes List of input files or directory for the analysis. Support formats: .wsp, .app, .dll, .exe, .zip.
LicenseFiles String Array No Optional path to SPCAF license files. If no license file is given only the free feature are activated.
SettingsFile String No Optional name or path to the settings files (.spruleset) which defines the analyzers for the analysis.
Reports String Array No List of report formats which should be generated during the analysis. Possible values: HTML, PDF, DOCX, XML, CSV, DGML.
OutputFile String No Optional path the output file. The reports will be written to the same location as the output file in the various formats.
Verbosity String No Optional level for verbosity to limit the detail level for log messages. Valid values are: quiet, minimal, normal, Default
TempDirectory String No Optional path to the temp folder.
SkipProjectCreation Boolean No Optional Boolean. Default FALSE. If TRUE no project (.spcaf) file is created as output of the analysis.
TimeOut Integer No Optional seconds after the analysis should be cancelled automatically.

Results

Apart from generating the detailled reports, SPCAF PowerShell outputs the number of issues to the console and provides the gathered information to the PowerShell pipe for further processing eg. to cancel the deployment.

Note: The number of issues is also available when running SPCAF PowerShell without a license making it easy to integrate in in every deployment process.

Sample Output:

CriticalErrors    : 1 
Errors            : 2 
CriticalWarnings  : 47 
Warnings          : 6 
Inventories       : 73 
Dependencies      : 7 
Metrics           : 103

Sample Reports

Additionally the following reports can be generated by the analysis (valid SPCAF Server Edition license required)

Code Quality Analysis HTML DOCX PDF XML CSV
Code Metrics HTML DOCX PDF XML CSV
Code Dependency Analysis HTML DOCX PDF XML CSV DGML
Code Inventory HTML DOCX PDF XML CSV
Code Migration Assessment HTML DOCX PDF XML

Try it now!

You can download the SPCAF PowerShell CmdLet from the TechNet Galleries

Download the SPCAF PowerShell CmdLet

Feedback

We would be very happy to hear your feedback about how you are using SPCAF PowerShell, so please tell us your experiences and feature requests either in the comments below or by mailing us to [email protected].

Thank you!

Merken

Matthias Einig

Matthias is a Microsoft MVP, co-founder, and CEO at Rencore. His mission is to helps enterprises stay in control of their Microsoft collaboration technology. Matthias and his team achieve this by providing insights, advice, and actionable ways to manage platform growth. Matthias is speaking at many conferences and community events all over the world and is one of the organizers of the European Collaboration Summit.