Skip to content

Instantly share code, notes, and snippets.

@victorvogelpoel
Last active December 23, 2015 19:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victorvogelpoel/6683232 to your computer and use it in GitHub Desktop.
Save victorvogelpoel/6683232 to your computer and use it in GitHub Desktop.
Source code belonging with blogpost at http://blog.victorvogelpoel.nl about testing a SharePoint 2007 deployment with PowerShell tests.Source code contains following PowerShell (v2) functions for SharePoint 2007: Get-SPFeature, Get-SPSolution, Add-SPSolution, Wait-SPSolutionJob, Install-SPSolution, Remove-SPSolution, Uninstall-SPSolution + Get-S…
# Test-PortalDeployment.ps1
# Written for SharePoint 2007, but with a few adaptations it'll work for later versions as well...
# This is a example of testing SharePoint portal artefact deployment and configuration using PSaint testing framework
# Victor Vogelpoel <victor@victorvogelpoel.nl>
# September 2013
# See blogpost at http://blog.victorvogelpoel.nl
#
# Note: SharePoint 2007 requires PowerShell v2 (not v3),
# so start PowerShell session with "PowerShell -version 2"
#
# Disclaimer
# This script is provided AS IS without warranty of any kind. I disclaim all implied warranties including, without limitation,
# any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or
# performance of the sample scripts and documentation remains with you. In no event shall I be liable for any damages whatsoever
# (including, without limitation, damages for loss of business profits, business interruption, loss of business information,
# or other pecuniary loss) arising out of the use of or inability to use the script or documentation.
Set-PSDebug -Strict
Set-StrictMode -Version Latest
# Allways stop at an error
$global:ErrorActionPreference = "Stop"
# Load SharePoint assemblies
[reflection.assembly]::LoadWithPartialName("Microsoft.SharePoint") | out-null
$PSScriptRoot = $MyInvocation.MyCommand.Path | Split-Path # Directory /Test/
function Initialize-TestFramework
{
[CmdletBinding(SupportsShouldProcess=$false)]
param
(
[Parameter(HelpMessage="If the test framework was loaded before, the force switch will unload the framework before loading it again")]
[switch]$Force
)
$modulesDirectory = Join-Path $PSScriptRoot "Modules" # Directory "/Test/Modules/
$rootDirectory = $script:modulesDirectory | Split-Path # Directory
$moduleNames = "Reflection", "PSaint"
$loadedModules = @(Get-Module $moduleNames | select -ExpandProperty name)
if (($loadedModules.Length -eq 0) -or $Force)
{
if ($loadedModules.Length -gt 0)
{
Write-Host "Unloading modules $($loadedModules -join ', ')."
Remove-Module $loadedModules -ErrorAction SilentlyContinue -Force
}
# Load Module Reflection and PSaint, TypeExtensions and FormatExtensions
Write-Host "Loading module: Reflection ..."
Import-Module "$modulesDirectory\Reflection\Reflection.psd1" -Force -Global
# if (!(Test-Path variable:global:ReflectionTypeExtensionLoaded))
# {
# Set-Variable -Name "ReflectionTypeExtensionLoaded" -Scope global -Value $true -Force
# Update-TypeData "$modulesDirectory\Reflection\extensionMethods.ps1xml"
# }
Write-Host "Loading module: PSaint ..."
Import-Module "$modulesDirectory\PSaint\PSaint.psd1" -Force -Global
}
<#
.SYNOPSIS
Initialize the PSaint test framework for use: load the PSaint module
.DESCRIPTION
Initialize the Testing framework by loading PSaint and Reflection
modules and Type-/Format extensions.
.PARAMETER Force
If the test framework was loaded before, the force switch will unload
the framework before loading it again.
Note that the type/format extensions cannot be reloaded.
.LINK
about_MacawPowerShell
about_MacawPowerShell_Tests
#>
}
##---------------------------------------------------------------------------------------------------------------------------------------------------
function Get-SPSolution
{
[CmdletBinding(SupportsShouldProcess=$false)]
param
(
[Parameter(Mandatory=$false, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Name of the solution")]
[Alias("SolutionName")]
[string[]]$Name = "*" # name can contain wildcards
)
process
{
foreach ($aName in $Name)
{
Write-Output ([Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions | where { $_.Name -like $aName})
}
}
<#
.SYNOPSIS
Get all solutions from the SharePoint solution store or the solution specified by name
.DESCRIPTION
.PARAMETER $Name
One or more names of the wsp to get the SPSolution; name may be a wildcard!
if not specified, all SPSolutions are returned;
.NOTES
Author : Victor Vogelpoel
.LINK
.EXAMPLE
[ps] Get-SPSolution | select name,deployed
Name Deployed
---- --------
lapointe.sharepoint.stsadm.commands.wsp True
radeditormoss.wsp True
.EXAMPLE
[ps] Get-SPSolution -name "radeditormoss.wsp" | select name
Name
----
radeditormoss.wsp
.EXAMPLE
[ps] Get-SPSolution -name "rad*.wsp" | select name
Name
----
radeditormoss.wsp
.EXAMPLE
[ps] Get-SPSolution -name "rad*.wsp", "lapointe*.wsp" | select name
Name
----
radeditormoss.wsp
lapointe.sharepoint.stsadm.commands.wsp
#>
}
#---------------------------------------------------------------------------------------------------------------------------------------------------
function Add-SPSolution
{
[CmdletBinding(SupportsShouldProcess=$false)]
param
(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Path to the WSP file")]
[Alias("Filename")]
[string[]]$Path
)
process
{
foreach ($wspfile in $Path)
{
if ($PSCmdLet.ShouldProcess("$wspfile", "Add-SPSolution `"$wspfile`""))
{
Write-Host "Adding SP solution `"$wspfile`"..."
trap { Write-Host "ERROR: $($_.Exception.Message)"; if ($_.Exception.Message -like "Access denied*") { throw "ERROR: executing account does not have proper permissions" } else {continue} }
Write-Output ([Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions.Add($wspfile))
}
}
}
}
function Wait-SPSolutionJob
{
[CmdletBinding(SupportsShouldProcess=$true, DefaultParameterSetName="SolutionName")]
param
(
[Parameter(Mandatory=$true, Position=0, ParameterSetName="SolutionName", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Name of the solution")]
[Alias("SolutionName")]
[string]$Name, # name can contain wildcards,
[Parameter(Mandatory=$true, Position=0, ParameterSetName="Solution", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Solution")]
[Alias("Solution")]
[Microsoft.SharePoint.Administration.SPSolution]$SPSolution
)
process
{
if ($psCmdlet.ParameterSetName -eq "Solution")
{
$Name = $SPSolution | Select -ExpandProperty Name
}
$solutions = Get-SPSolution -name $Name
if ($solutions)
{
foreach ($solution in $solutions)
{
$solutionName = $solution.Name
if ($solution.JobExists)
{
$waitForMax = 720 # after 720*5 = 3600 seconds , the script should exit
while ($waitForMax -gt 0 -and
$solution.JobExists -and
(($solution.JobStatus -eq [Microsoft.SharePoint.Administration.SPRunningJobStatus]::Initialized) -or
($solution.JobStatus -eq [Microsoft.SharePoint.Administration.SPRunningJobStatus]::Scheduled)))
{
$waitForMax--
Write-Host "Job for solution `"$solutionName`" is `"$($solution.JobStatus)`". (Waiting 5 seconds for next update...)"
Start-Sleep -Seconds 5 # wait 5 second
# Re-get the solution object
$solution = Get-SPSolution -name $solutionName
}
}
}
}
else
{
Write-Verbose "No solution found for name `"$name`": nothing to wait for."
}
}
}
function Install-SPSolution
{
[CmdletBinding(SupportsShouldProcess=$true, DefaultParameterSetName="SolutionName")]
param
(
[Parameter(Mandatory=$true, Position=0, ParameterSetName="SolutionName", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Name of the solution")]
[Alias("SolutionName")]
[string[]]$Name, # name can contain wildcards,
[Parameter(Mandatory=$true, Position=0, ParameterSetName="Solution", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Solution")]
[Alias("Solution")]
[Microsoft.SharePoint.Administration.SPSolution[]]$SPSolution,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Optional URL to retract the solution from")]
[string]$Url = "",
[Parameter(Mandatory=$false, HelpMessage="Optional to deploy the solution to all Content URLs")]
[switch]$AllContentUrls,
[Parameter(Mandatory=$false, HelpMessage="Optional to indicate that deployment to GAC is allowed")]
[switch]$AllowGACDeployment,
[Parameter(Mandatory=$false, HelpMessage="Optional to force deployment of the solution")]
[switch]$Force
)
begin
{
$dateToGuaranteeInstantAction = [datetime]::Now.AddDays(-2)
$whatif = ($PSBoundParameters["Whatif"] -eq $true)
}
process
{
if ($psCmdlet.ParameterSetName -eq "Solution")
{
$Name = $SPSolution | Select -ExpandProperty Name
}
$solutions = Get-SPSolution -name $name
foreach ($solution in $solutions)
{
if ($solution)
{
$solutionName = $solution.Name
# Construct a commandtext
$verboseCommand = "Install-SPSolution $solutionName"
if (!([string]::IsNullOrEmpty($url))) { $verboseCommand = ($verboseCommand + " to url=$url" ) }
elseif ($allContentUrls) { $verboseCommand = ($verboseCommand + " to all content urls" ) }
$verboseCommand = ($verboseCommand + ", allowGACDeployment=$allowGACDeployment, force=$force")
if ($PSCmdLet.ShouldProcess("Solution `"$($solution.Name)`" on url=$url, allcontenturls=$allContentUrls", "Install-SPSolution"))
{
if ($solution.ContainsWebApplicationResource)
{
$webApplicationsCollection = $null
$verboseText = ""
if ($allContentUrls)
{
# Get all content webapplications
$webApplicationsCollection = Get-SPWebApplicationCollection
$verboseText = "all content URLs"
}
elseif ([string]::IsNullOrEmpty($url))
{
throw "ERROR: Solution contains webapplication resources; please specify -url or -AllContentUrls"
}
else
{
# Get the webapplication for the specified url
$webApplicationsCollection = Get-SPWebApplicationCollection -url $url
if (!$webApplicationsCollection) { throw "ERROR: Cannot find webapplication with url `"$url`"" }
$verboseText = $url
}
Write-Host "Deploying $solutionName to $verboseText allowGACDeployment=$allowGACDeployment, force=$force..."
trap { Write-Host "ERROR: $($_.Exception.Message)"; if ($_.Exception.Message -like "Access denied*") { throw "ERROR: executing account does not have proper permissions" } else {continue} }
$solution.Deploy($dateToGuaranteeInstantAction, $allowGACDeployment, $webApplicationsCollection, $force)
}
else
{
Write-Host ("Deploying $solutionName globally; allowGACDeployment=$allowGACDeployment, force=$force...")
trap { Write-Host "ERROR: $($_.Exception.Message)"; if ($_.Exception.Message -like "Access denied*") { throw "ERROR: executing account does not have proper permissions" } else {continue} }
$solution.Deploy($dateToGuaranteeInstantAction, $allowGACDeployment, $force)
}
# Allways wait for the job to finish (or for a timeout)
Wait-SPSolutionJob -name $solutionName
# Now test if the deployment was successful:
$testsolution = Get-SPSolution -name $solutionName
if ($testsolution)
{
if ($testsolution.LastOperationResult -ne "DeploymentSucceeded")
{
throw "ERROR: solution `"$solutionName`" deployment failed; LastOperationResult is $($testsolution.LastOperationResult); Details: $($testsolution.LastOperationDetails)"
}
Write-Host $testsolution.LastOperationDetails
}
}
}
else
{
if ($whatif)
{
Write-Host "What if: cannot find any solutions with name `"$Name`"; deployment aborted"
}
else
{
throw "ERROR: cannot find any solutions with name `"$Name`"; deployment aborted"
}
}
}
}
}
##---------------------------------------------------------------------------------------------------------------------------------------------------
# Get-SPWebApplicationCollection gets a typed generic Collection<SPWebApplication>
function Get-SPWebApplicationCollection
{
[CmdletBinding(SupportsShouldProcess=$false)]
param
(
[Parameter(Mandatory=$false, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="URL of any zone in the SharePoint webapp to return the WebApplication object(s) for")]
[string]$url = ""
)
process
{
Enter
try
{
$coll = New-GenericObject2 -typename System.Collections.ObjectModel.Collection -typeParameters ([Microsoft.SharePoint.Administration.SPWebApplication])
# Copy collection...
Get-SPWebApplication -url $url | foreach { $coll.psbase.Add($_) }
#explanation of oddball return syntax lies here:
#http://stackoverflow.com/questions/695474
return @(,$coll)
}
finally
{
Leave
}
}
}
# http://www.leeholmes.com/blog/CreatingGenericTypesInPowerShell.aspx
function New-GenericObject2
{
param(
[string] $typeName = $(throw "Missing: a generic type name"),
[string[]] $typeParameters = $(throw "Missing: the type parameters"),
[object[]] $constructorParameters
)
## Create the generic type name
$genericTypeName = $typeName + '`' + $typeParameters.Count
$genericType = [Type] $genericTypeName
if(-not $genericType)
{
throw "Could not find generic type $genericTypeName"
}
## Bind the type arguments to it
[type[]] $typedParameters = $typeParameters
$closedType = $genericType.MakeGenericType($typedParameters)
if(-not $closedType)
{
throw "Could not make closed type $genericType"
}
## Create the closed version of the generic type
$instance = ,[Activator]::CreateInstance($closedType, $constructorParameters)
return $instance
}
function Remove-SPSolution
{
[CmdletBinding(SupportsShouldProcess=$true, DefaultParameterSetName="SolutionName")]
param
(
[Parameter(Mandatory=$true, Position=0, ParameterSetName="SolutionName", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Name of the solution")]
[Alias("SolutionName")]
[string[]]$Name, # name can contain wildcards,
[Parameter(Mandatory=$true, Position=0, ParameterSetName="Solution", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Solution")]
[Alias("Solution")]
[Microsoft.SharePoint.Administration.SPSolution[]]$SPSolution
)
process
{
$whatif = ($PSBoundParameters["Whatif"] -eq $true)
if ($psCmdlet.ParameterSetName -eq "Solution")
{
$Name = $SPSolution | Select -ExpandProperty Name
}
foreach ($solname in $Name)
{
$solutions = Get-SPSolution -name $solname
if ($solutions)
{
foreach ($solution in $solutions)
{
if ($solution)
{
if ($PSCmdLet.ShouldProcess($solution.Name, "Remove-SPSolution"))
{
Write-Host "Deleting SP Solution $($solution.Name)..."
trap { Write-Host "ERROR: $($_.Exception.Message)"; if ($_.Exception.Message -like "Access denied*") { throw "ERROR: executing account does not have proper permissions" } else {continue} }
$solution.Delete()
}
}
}
}
else
{
if ($whatif)
{
Write-Host "What if: cannot find any solutions with name `"$Name`"'; nothing is deleted"
}
else
{
throw "ERROR: No solution(s) found in SharePoint solution store with name `"$Name`""
}
}
}
}
}
function Uninstall-SPSolution
{
[CmdletBinding(SupportsShouldProcess=$true, DefaultParameterSetName="SolutionName")]
param
(
[Parameter(Mandatory=$true, Position=0, ParameterSetName="SolutionName", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Name of the solution")]
[Alias("SolutionName")]
[string[]]$Name, # name can contain wildcards,
[Parameter(Mandatory=$true, Position=0, ParameterSetName="Solution", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Solution")]
[Alias("Solution")]
[Microsoft.SharePoint.Administration.SPSolution[]]$SPSolution,
[Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true, HelpMessage="Optional URL to retract the solution from")]
[string]$Url = "",
[Parameter(Mandatory=$false, HelpMessage="Optional to retract the solution from all Content URLs")]
[switch]$allContentUrls
)
begin
{
$dateToGuaranteeInstantAction = [datetime]::Now.AddDays(-2)
$whatif = ($PSBoundParameters["Whatif"] -eq $true)
}
process
{
if ($psCmdlet.ParameterSetName -eq "Solution")
{
$Name = $SPSolution | Select -ExpandProperty Name
}
#$solutions = [Microsoft.SharePoint.Administration.SPFarm]::Local.Solutions[$wspname]
$solutions = Get-SPSolution -name $Name
if ($solutions)
{
foreach ($solution in $solutions)
{
if ($solution)
{
$solutionName = $solution.Name
if ($PSCmdLet.ShouldProcess("Solution `"$($solution.Name)`" on url=$url, allcontenturls=$allContentUrls", "Retract-SPSolution"))
{
if ($solution.ContainsWebApplicationResource)
{
# retract from webapplications
$webApplicationsCollection = $null
$verboseText = ""
if ($allContentUrls)
{
# Get all content webapplications
$webApplicationsCollection = Get-SPWebApplicationCollection
$verboseText = "all content URLs"
}
elseif ([string]::IsNullOrEmpty($url))
{
throw "ERROR: Solution contains webapplication resources; please specify -url or -AllContentUrls"
}
else
{
# Get the webapplication for the specified url
$webApplicationsCollection = Get-SPWebApplicationCollection -url $url
if ($webApplicationsCollection -eq $null)
{
throw "ERROR: cannot find webapplication for $url; aborting retract"
}
$verboseText = $url
}
Write-Host "Retracting SP Solution `"$($solution.Name)`" from $verboseText..."
# Retract from the webapplication; SharePoint adds a job that is executed by the Timer service
trap { Write-Host "ERROR: $($_.Exception.Message)"; if ($_.Exception.Message -like "Access denied*") { throw "ERROR: executing account does not have proper permissions" } else {continue} }
$solution.Retract($dateToGuaranteeInstantAction, $webApplicationsCollection)
}
else
{
Write-Host "Retracting SP Solution `"$($solution.Name)`" globally..."
# Retract globally; SharePoint adds a job that is executed by the Timer service
trap { Write-Host "ERROR: $($_.Exception.Message)"; if ($_.Exception.Message -like "Access denied*") { throw "ERROR: executing account does not have proper permissions" } else {continue} }
$solution.Retract($dateToGuaranteeInstantAction)
}
# Always wait for the job to finish
Wait-SPSolutionJob -name $solutionName
# Now test if the retraction was successful:
$testsolution = Get-SPSolution -name $solutionName
if ($testsolution)
{
if ($testsolution.LastOperationResult -ne "RetractionSucceeded")
{
throw "ERROR: solution $solutionName retraction failed; LastOperationResult is $($testsolution.LastOperationResult); Details: $($testsolution.LastOperationDetails)"
}
Write-Host $testsolution.LastOperationDetails
}
}
else
{
Write-Verbose "Retract-SPSolution: ShouldProcess yielded false: solution `"$($solution.Name)`" was not retracted."
}
}
}
}
else
{
if ($Whatif)
{
Write-Host "What if: cannot find any solutions with name `"$Name`"'; nothing is retracted"
}
else
{
throw "ERROR: cannot find any solution for `"$Name`" in the solution store. Retract aborted"
}
}
}
}
function Get-SPWebApplication
{
[CmdletBinding(SupportsShouldProcess=$false)]
param
(
[Parameter(Mandatory=$false, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="URL of any zone in the SharePoint webapp to return the WebApplication object(s) for")]
[string]$url = ""
)
process
{
try
{
Write-Output ([Microsoft.SharePoint.Administration.SPWebService]::ContentService.WebApplications | where {
$url -eq "" -or (
$_.GetResponseUri([Microsoft.SharePoint.Administration.SPUrlZone]::Default) -eq $url -or
$_.GetResponseUri([Microsoft.SharePoint.Administration.SPUrlZone]::Intranet) -eq $url -or
$_.GetResponseUri([Microsoft.SharePoint.Administration.SPUrlZone]::Internet) -eq $url -or
$_.GetResponseUri([Microsoft.SharePoint.Administration.SPUrlZone]::Extranet) -eq $url -or
$_.GetResponseUri([Microsoft.SharePoint.Administration.SPUrlZone]::Custom) -eq $url)
})
}
catch
{
Write-Error "ERROR while getting SharePoint webapplication object for url `"$url`": $_"
Write-Error "Please check event log for errors, which may include problems logging in into the SharePoint databases"
}
}
}
##---------------------------------------------------------------------------------------------------------------------------------------------------
function Get-SPFeature
{
[CmdLetBinding(SupportsShouldProcess=$false, defaultParameterSetname="IdentityOnly")]
param
(
[Parameter(Position=0, Mandatory=$false, parameterSetName="IdentityOnly", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Id of the feature")]
[Parameter(Position=0, Mandatory=$false, parameterSetName="Farm", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Id of the feature")]
[Parameter(Position=0, Mandatory=$false, parameterSetName="Web", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Id of the feature")]
[Parameter(Position=0, Mandatory=$false, parameterSetName="Site", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Id of the feature")]
[Parameter(Position=0, Mandatory=$false, parameterSetName="WebApplication", ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true, HelpMessage="Id of the feature")]
[string]$Identity = "",
[Parameter(Mandatory=$false, parameterSetName="Farm", ValueFromPipelineByPropertyName=$true, HelpMessage="Specifies that if this parameter is used, only enabled farm Features are displayed.")]
[switch]$Farm,
[Parameter(Mandatory=$true, parameterSetName="Site", ValueFromPipelineByPropertyName=$true, HelpMessage="Specifies the SPSite to find the features for")]
[Microsoft.SharePoint.SPSite]$Site,
[Parameter(Mandatory=$true, parameterSetName="Web", ValueFromPipelineByPropertyName=$true, HelpMessage="Specifies the SPWeb to find the features for")]
[Microsoft.SharePoint.SPWeb]$Web,
[Parameter(Mandatory=$true, parameterSetName="WebApplication", ValueFromPipelineByPropertyName=$true, HelpMessage="Specifies the URL of the webapplication to get features for")]
[Alias("url")]
[string]$WebAppUrl,
[Parameter(Mandatory=$false, parameterSetName="IdentityOnly", ValueFromPipelineByPropertyName=$true, HelpMessage="Limits the display result; if 'all' is specified, all features are displayed; if a number, the number must be greater than 0; default value is 200")]
[Parameter(Mandatory=$false, parameterSetName="Farm", ValueFromPipelineByPropertyName=$true, HelpMessage="Limits the display result; if 'all' is specified, all features are displayed; if a number, the number must be greater than 0; default value is 200")]
[Parameter(Mandatory=$false, parameterSetName="Web", ValueFromPipelineByPropertyName=$true, HelpMessage="Limits the display result; if 'all' is specified, all features are displayed; if a number, the number must be greater than 0; default value is 200")]
[Parameter(Mandatory=$false, parameterSetName="Site", ValueFromPipelineByPropertyName=$true, HelpMessage="Limits the display result; if 'all' is specified, all features are displayed; if a number, the number must be greater than 0; default value is 200")]
[Parameter(Mandatory=$false, parameterSetName="WebApplication", ValueFromPipelineByPropertyName=$true, HelpMessage="Limits the display result; if 'all' is specified, all features are displayed; if a number, the number must be greater than 0; default value is 200")]
[ValidateScript({ $limitInt = 0; ($Limit -eq "All" -or ([int]::TryParse($Limit, [ref]$limitInt) -and $limitInt -gt 0 )) })]
[string]$Limit = "200"
)
# SPFarm.FeatureDefinitions Returns the list of all installed features in the server farm.
# SPWebApplication.Features Returns a list of activated virtual server-scoped features for the SharePoint Foundation Web application.
# SPWebService.Features Returns the administrative features that have been activated at the server farm scope.
# SPSite.Features Returns the list of activated features for the site collection.
# SPWeb.Features Returns the list of activated features for a site.
# SPFeatureDefinition.ActivationDependencies Returns the list of features upon which activation of another feature depends.
# QueryFeatures(Guid) Returns a list of all of the site collection-scoped and Web site-scoped features of the given GUID.
begin
{
$allFeatures = [Microsoft.SharePoint.Administration.SPFarm]::Local.FeatureDefinitions
$webapplicationFeatures = $null
switch ($PSCmdlet.ParameterSetName)
{
"Site" { $siteFeatures = $site.Features }
"web" { $webFeatures = $web.Features }
"webapplication"
{
$webapp = Get-SPWebApplication -url $WebAppUrl
if ($webapp)
{
$webapplicationFeatures = $webapp.Features
}
else
{
throw "Cannot find SharePoint WebApplication for URL `"$WebAppUrl`""
}
}
}
}
process
{
$limitInt = [int]::MaxValue
if ($Limit -ne "All")
{
$limitInt = [int]$Limit
}
switch ($PSCmdlet.ParameterSetName)
{
"IdentityOnly"
{
$allFeatures | where { $Identity -eq "" -or $_.Id -eq $Identity -or $_.DisplayName -eq $Identity } | select -First $limitInt
break;
}
"Farm"
{
$allFeatures | where { $_.Scope -eq "Farm" -and ($Identity -eq "" -or $_.Id -eq $Identity -or $_.DisplayName -eq $Identity) } | select -First $limitInt
break;
}
"Site"
{
$siteFeatures | select -ExpandProperty Definition | where { $Identity -eq "" -or $_.Id -eq $Identity -or $_.DisplayName -eq $Identity } | select -First $limitInt
break;
}
"Web"
{
$webFeatures | select -ExpandProperty Definition | where { $Identity -eq "" -or $_.Id -eq $Identity -or $_.DisplayName -eq $Identity } | select -First $limitInt
break;
}
"WebApplication"
{
$webapplicationFeatures | select -ExpandProperty Definition | where { $Identity -eq "" -or $_.Id -eq $Identity -or $_.DisplayName -eq $Identity } | select -First $limitInt
break;
}
default
{
throw "Cannot find parametersetName `"$($PSCmdlet.ParameterSetName)`""
}
}
}
}
##---------------------------------------------------------------------------------------------------------------------------------------------------
# Initialize PSaint
Initialize-TestFramework
##---------------------------------------------------------------------------------------------------------------------------------------------------
Test-Code "Solution `"framework_v1*.WSP`" is installed in SharePoint solution store" {
arrange {
$solutionName = "framework_v1*.WSP"
}
act {
$solution = Get-SPSolution $solutionName # NOTE: mijn Get-SPSolution voor SharePoint 2007 ondersteunt wildcards!
}
assert {
Assert-That { $solution –ne $null } -FailMessage "Solution `"$solutionName`" not found in solution store"
}
}
# Above Test-Code call will yield a TestResult object like this:
# Result Name FailMessage
# ------ ---- --------
# Fail Solution framework_v*.WSP is installed in solution store Solution "framework_v*.WSP" not found in solution store
##---------------------------------------------------------------------------------------------------------------------------------------------------
Test-Code "Feature `"Error Page control adapter`" is activated (at web application scope)" {
arrange {
$webAppUrl = "http://portal.nl"
$featureIdentity = "Feature-ErrorPageControlAdapter"
$featureIsInstalled = $false
$webAppScopedFeatureIsActivated = $false
}
act {
# Get the feature from the list of all installed features in the server farm
$feature = Get-SPFeature -Identity $featureIdentity
$featureIsInstalled = ($feature -ne $null -and $feature.Status -eq "Online")
if ($featureIsInstalled)
{
$webAppScopedFeatureIsActivated = ((Get-SPFeature -Identity $featureIdentity -WebAppUrl $webAppUrl) -ne $null)
}
}
assert {
Assert-That { $featureIsInstalled } -FailMessage "Feature `"$featureIdentity`" is not installed in the farm."
Assert-That { $webAppScopedFeatureIsActivated } -FailMessage "Feature `"$featureIdentity`" is not activated at webapplication `"$webAppUrl`"."
}
}
# Above Test-Code call will yield a TestResult object like this:
# Result Name FailMessage
# ------ ---- --------
# Fail Solution framework_v*.WSP is installed in solution store Solution "framework_v*.WSP" not found in solution store
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment