Powershell Assertion Framework

# Based upon: http://www.leeholmes.com/blog/2005/09/05/unit-testing-in-powershell-%E2%80%93-a-link-parser/
# Updated to Powershell 2

Set-StrictMode -Version Latest

## A simple assert function.  Verifies that $condition
## is true.  If not, outputs the specified error message.
function assert
{
param
(
[Parameter(Mandatory=$True)]
[bool] $condition,
[string] $message = “Test failed.”
)

if(-not $condition)
{
write-host “FAIL. $message”
}
else
{
write-host -NoNewLine “.”
}
}

## A simple “assert equals” function.  Verifies that $expected
## is equal to $actual.  If not, outputs the specified error message.
function assertEquals
{
param
(
[Parameter(Mandatory=$True)]
[AllowNull()]
$expected,
[Parameter(Mandatory=$True)]
[AllowNull()]
$actual,
[string] $message = “Test failed.”
)

if(-not ($expected -eq $actual))
{
write-host “FAIL.  Expected: ‘$expected’.  Actual: ‘$actual’.  $message.”
}
else
{
write-host -NoNewLine “.”;
}
}

Simple MEF Example

using System;
using System.ComponentModel.

Composition; // This is the assembly
using System.ComponentModel.Composition.Hosting;
using System.Reflection;

namespace SimpleMEF
{
public class Class1
{
static void Main()
{
AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
CompositionContainer container = new CompositionContainer(catalog);

User user = new User();
container.ComposeParts(user);
user.Start();
Console.ReadLine();
}
}

class User
{
[Import]
private IExecute execute;

public void Start()
{
Console.WriteLine(execute.Execute());
}
}

[InheritedExport]
public interface IExecute
{
string Execute();
}

class First : IExecute
{

public string Execute()
{
return “First”;
}
}
}

Useful powershell about_ commands

powershells get-help system is wonderful (not quite sure about the new update-help).

Here are some useful get-help topics:

about_Aliases                     HelpFile                            Describes how to use alternate names for cmdlets and commands in Windows
about_Arithmetic_Operators        HelpFile                            Describes the operators that perform arithmetic in Windows PowerShell.
about_Arrays                      HelpFile                            SHORT DESCRIPTION
about_Assignment_Operators        HelpFile                            Describes how to use operators to assign values to variables.
about_Automatic_Variables         HelpFile                            Describes variables that store state information for Windows PowerShell.
about_Break                       HelpFile                            Describes a statement you can use to immediately exit Foreach, For, While,
about_Command_Precedence          HelpFile                            Describes how Windows PowerShell determines which command to run.
about_Command_Syntax              HelpFile                            Describes the syntax diagrams that are used in Windows PowerShell.
about_Comment_Based_Help          HelpFile                            SHORT DESCRIPTION
about_CommonParameters            HelpFile                            SHORT DESCRIPTION
about_Comparison_Operators        HelpFile                            SHORT DESCRIPTION
about_Continue                    HelpFile                            Describes how the Continue statement immediately returns the program flow
about_Core_Commands               HelpFile                            Lists the cmdlets that are designed for use with Windows PowerShell
about_Data_Sections               HelpFile                            Explains Data sections, which isolate text strings and other read-only
about_Debuggers                   HelpFile                            Describes the Windows PowerShell debugger.
about_Do                          HelpFile                            Runs a statement list one or more times, subject to a While or Until
about_Environment_Variables       HelpFile                            Describes how to access Windows environment variables in Windows
about_Escape_Characters           HelpFile                            Introduces the escape character in Windows PowerShell and explains
about_Eventlogs                   HelpFile                            Windows PowerShell creates a Windows event log that is
about_Execution_Policies          HelpFile                            Describes the Windows PowerShell execution policies and explains
about_For                         HelpFile                            SHORT DESCRIPTION
about_Foreach                     HelpFile                            Describes a language command you can use to traverse all the items in a
about_Format.ps1xml               HelpFile                            The Format.ps1xml files in Windows PowerShell define the default display
about_Functions                   HelpFile                            Describes how to create and use functions in Windows PowerShell.
about_Functions_Advanced          HelpFile                            Introduces advanced functions that act similar to cmdlets.
about_Functions_Advanced_Methods  HelpFile                            Describes how functions that specify the CmdletBinding attribute can use
about_Functions_Advanced_Param… HelpFile                            Explains how to add parameters to advanced functions.
about_Functions_CmdletBindingA… HelpFile                            Describes the attribute that makes a function work like a
about_Functions_OutputTypeAttr… HelpFile                            SHORT DESCRIPTION
about_Group_Policy_Settings       HelpFile                            Describes the Group Policy settings for Windows PowerShell
about_Hash_Tables                 HelpFile                            SHORT DESCRIPTION
about_History                     HelpFile                            Describes how to get and run commands in the command history.
about_If                          HelpFile                            Describes a language command you can use to run statement lists based
about_Jobs                        HelpFile                            Provides information about how Windows PowerShell background jobs run a
about_Job_Details                 HelpFile                            SHORT DESCRIPTION
about_Join                        HelpFile                            SHORT DESCRIPTION
about_Language_Keywords           HelpFile                            SHORT DESCRIPTION
about_Line_Editing                HelpFile                            Describes how to edit commands at the Windows PowerShell command prompt.
about_Locations                   HelpFile                            Describes how to access items from the working location in Windows
about_Logical_Operators           HelpFile                            Describes the operators that connect statements in Windows PowerShell.
about_Methods                     HelpFile                            Describes how to use methods to perform actions on objects in Windows
about_Modules                     HelpFile                            Explains how to install, import, and use Windows PowerShell modules.
about_Objects                     HelpFile                            SHORT DESCRIPTION
about_Object_Creation             HelpFile                            SHORT DESCRIPTION
about_Operators                   HelpFile                            Describes the operators that are supported by Windows PowerShell.
about_Operator_Precedence         HelpFile                            Lists the Windows PowerShell operators in precedence order.
about_Parameters                  HelpFile                            SHORT DESCRIPTION
about_Parameters_Default_Values   HelpFile                            SHORT DESCRIPTION
about_Parsing                     HelpFile                            Describes how Windows PowerShell parses commands.
about_Path_Syntax                 HelpFile                            Describes the full and relative path name formats in Windows PowerShell.
about_Pipelines                   HelpFile                            Combining commands into pipelines in the Windows PowerShell
about_PowerShell.exe              HelpFile                            Explains how to use the PowerShell.exe command-line tool. Displays
about_PowerShell_Ise.exe          HelpFile                            Explains how to use the PowerShell_Ise.exe command-line tool.
about_Preference_Variables        HelpFile                            Variables that customize the behavior of Windows PowerShell
about_Profiles                    HelpFile                            Describes how to create and use a Windows PowerShell profile.
about_Prompts                     HelpFile                            SHORT DESCRIPTION
about_Properties                  HelpFile                            Describes how to use object properties in Windows PowerShell.
about_Providers                   HelpFile                            Describes how Windows PowerShell providers provide access to data and
about_PSSessions                  HelpFile                            Describes Windows PowerShell sessions (PSSessions) and explains how to
about_PSSession_Details           HelpFile                            Provides detailed information about Windows PowerShell sessions and the
about_PSSnapins                   HelpFile                            Describes Windows PowerShell snap-ins and shows how to use and manage them.
about_Quoting_Rules               HelpFile                            SHORT DESCRIPTION
about_Redirection                 HelpFile                            Explains how to redirect output from Windows PowerShell to text files.
about_Ref                         HelpFile                            Describes how to create and use a reference variable type.
about_Regular_Expressions         HelpFile                            Describes regular expressions in Windows PowerShell.
about_Remote                      HelpFile                            Describes how to run remote commands in Windows PowerShell.
about_Remote_Disconnected_Sess… HelpFile                            Explains how to disconnect from and reconnect to a PSSession
about_Remote_FAQ                  HelpFile                            Contains questions and answers about running remote commands
about_Remote_Jobs                 HelpFile                            Describes how to run background jobs on remote computers.
about_Remote_Output               HelpFile                            Describes how to interpret and format the output of remote commands.
about_Remote_Requirements         HelpFile                            Describes the system requirements and configuration requirements for
about_Remote_Troubleshooting      HelpFile                            Describes how to troubleshoot remote operations in Windows PowerShell.
about_Remote_Variables            HelpFile                            Explains how to use local and remote variables in remote
about_Requires                    HelpFile                            Prevents a script from running without the required elements.
about_Reserved_Words              HelpFile                            Lists the reserved words that cannot be used as identifiers because they
about_Return                      HelpFile                            Exits the current scope, which can be a function, script, or script block.
about_Run_With_PowerShell         HelpFile                            Explains how to use the “Run with PowerShell” feature to run
about_Scopes                      HelpFile                            Explains the concept of scope in Windows PowerShell and shows how to set
about_Scripts                     HelpFile                            Describes how to run and write scripts in Windows PowerShell.
about_Script_Blocks               HelpFile                            Defines what a script block is and explains how to use script blocks in
about_Script_Internationalization HelpFile                            Describes the script internationalization features of Windows PowerShell 2.0
about_Session_Configurations      HelpFile                            Describes session configurations, which determine the users who can
about_Session_Configuration_Files HelpFile                            Describes session configuration files, which can be used in a
about_Signing                     HelpFile                            SHORT DESCRIPTION
about_Special_Characters          HelpFile                            Describes the special characters that you can use to control how
about_Splatting                   HelpFile                            SHORT DESCRIPTION
about_Split                       HelpFile                            Explains how to use the Split operator to split one or more strings into
about_Switch                      HelpFile                            SHORT DESCRIPTION
about_Throw                       HelpFile                            Describes the Throw keyword, which generates a terminating error.
about_Transactions                HelpFile                            Describes how to manage transacted operations in Windows PowerShell.
about_Trap                        HelpFile                            Describes a keyword that handles a terminating error.
about_Try_Catch_Finally           HelpFile                            Describes how to use the Try, Catch, and Finally blocks to handle
about_Types.ps1xml                HelpFile                            Explains how to use Types.ps1xml files to extend the types of objects
about_Type_Operators              HelpFile                            Describes the operators that work with Microsoft .NET Framework types.
about_Updatable_Help              HelpFile                            SHORT DESCRIPTION
about_Variables                   HelpFile                            Describes how variables store values that can be used in Windows
about_While                       HelpFile                            Describes a language statement that you can use to run a command block
about_Wildcards                   HelpFile                            Describes how to use wildcard characters in Windows PowerShell.
about_Windows_PowerShell_3.0      HelpFile                            Describes some of the new features that are included in
about_Windows_PowerShell_ISE      HelpFile                            SHORT DESCRIPTION
about_WMI                         HelpFile                            SHORT DESCRIPTION
about_Wmi_Cmdlets                 HelpFile                            Provides background information about Windows Management Instrumentation
about_WQL                         HelpFile                            SHORT DESCRIPTION
about_WS-Management_Cmdlets       HelpFile                            Provides an overview of Web Services for Management (WS-Management) as

Minimal Scaffolding for Visual Studio

Here is an article that explains the setup.

However to get started in four lines:

New Project
From NuGet Console:
Install-Package t4scaffolding
Scaffold CustomScaffolder MinimalDemo

Then you can simply use:
scaffold MinimalDemo -Project MinimalScaffolding

I will experiment with performing database and filessytem queries.

The demo project creates a MinimalDemo.ps1 and a minimal demo t4 template.

The demo looks like:

[T4Scaffolding.Scaffolder(Description = “Enter a description of MinimalDemo here”)][CmdletBinding()]
param(
[string]$Project,
[string]$CodeLanguage,
[string[]]$TemplateFolders,
[switch]$Force = $false,
[string]$Filename = “ExampleOutput”
)

$outputPath = $Filename  # The filename extension will be added based on the template’s <#@ Output Extension=”…” #> directive
$namespace = (Get-Project $Project).Properties.Item(“DefaultNamespace”).Value

Add-ProjectItemViaTemplate $outputPath -Template MinimalDemoTemplate `
-Model @{ Namespace = $namespace; ExampleValue = “Hello, world!” } `
-SuccessMessage “Added MinimalDemo output at {0}” `
-TemplateFolders $TemplateFolders -Project $Project -CodeLanguage $CodeLanguage -Force:$Force

Note in this instance I have edited the param list to allow the filename to be specified on the command line.

Since data is passed into the template via the model parameter it is trivial to perform database or filesystem queries to enrich the data being passed to the item generated.

Combine this with version control and you can overwrite the existing version and merge back existing customisations.

We have MVC style one-shot code generation (with the force option to overwrite).

This is incredibly powerful. A few of these templates could save hours of work. Especially across a team.

Command Line TFS Access

There are a couple of useful powershell command-line tools that are of use:

This is useful to query tasks and work items

tfpt query “ProjectPath to query”

From a mapped folder allows the running of existing tfs work item queries from the command-line

It uses the current folders mapping to identify the project.

This is useful for quering checkins:

Run from the VS2012 command prompt:

tf history x:path_to_project /recursive /noprompt /user:”My User Name”